其他分享
首页 > 其他分享> > webapi读取配置文件内容

webapi读取配置文件内容

作者:互联网

1.读取默认的配置文件appsettings.json

appsettings.json内容
{ "Logging": {"Default": "Information", "Microsoft": "Warning", }, "AllowedHosts": "*", "ConnectionString": "Server=.;Database=Carina;User ID=sa;Password=pass****;" }

 

public class WeatherForecastController : ControllerBase
  {
    private IConfiguration _configuration;

    private readonly ILogger<WeatherForecastController> _logger;
  //依赖注入configuration,就可以在controller中使用configuration了
    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
      _logger = logger;
      _configuration = configuration;  //
    }
  //读取单个值
  var connectionStr =_configuration["ConnectionString"] ;
  //var connectionStr =_configuration.GetValue<string>("ConnectionString")
  //获取对象中的值
  var connectionStr =_configuration["Logging:Default"] //返回”Information“
}

若要读出一个对象,需要先声明一个类,然后读取出来。若要依赖注入该配置文件对象,需要再startup类中声明

public class Logging{
      public string Default{get;set;},
      public string Microsoft{get;set}
}

//controller类中
var config = _configuration.GetSection("logging1").Get<Logging>();

//若要依赖注入配置文件的对象。 //startup类 public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.Configure<Logging>(Configuration.GetSection("Logging")); } //controller类中 private IConfiguration _configuration; private Logging logging; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration, IOptions<Logging> options) { _logger = logger; _configuration = configuration; logging = options.Value; //logging对象即包含配置文件的信息 }

  单独类读取配置文件信息

  public static class ConfigurationManager
    {
        public readonly static IConfiguration Configuration;

        static ConfigurationManager()
        {
            Configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .Build();
        }

        public static T GetSection<T>(string key) where T : class, new()
        {
            return new ServiceCollection()
                .AddOptions()
                .Configure<T>(Configuration.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
        }

        public static string GetSection(string key)
        {
            return Configuration.GetValue<string>(key);
        }
    }

 

标签:webapi,GetSection,读取,配置文件,logger,configuration,public,string
来源: https://www.cnblogs.com/kingsmart/p/14985113.html