欢迎光临
个人技术文档整理

.Net Core 读取配置文件的几种方式(Configuration)

配置 appsettings.json 信息

{ 
  "AppSettings": {
    "IsDebug": true,
    "Version": "1.0.0",
    "Name": "文哥" 
  }
}

创建 一个配置对应类 AppSettingsOptions.cs

    public class AppSettingsOptions
    {
        public bool IsDebug { get; set; }
        public string Name { get; set; } 
        public string Version { get; set; }
    }

依赖注入 IConfiguration 读取 appsettings.json 信息

  • 构造函数注入方式
            private readonly IConfiguration _configuration;
            public DemoController(IConfiguration configuration)
            {
                _configuration = configuration;
            }
  • 参数注入方式 [FromServices]
            [HttpGet]
            public string Get([FromServices] IConfiguration configuration)
            { 
                var data = App.Configuration.GetSection("AppSettings").Get<AppSettingsOptions>();//对象 
                var name = configuration["AppSettings:Name"]; //文哥 
                var isDebug = configuration.GetValue<bool>("AppSettings:IsDebug"); // true 
                var version = configuration.GetSection("AppSettings").GetSection("Version").Value; // 1.0.0 
                return version;
            }

 

选项模式读取 appsettings.json 信息

  1. 需在Startup.cs注册
            public void ConfigureServices(IServiceCollection services)
            { 
                services.Configure<AppSettingsOptions>(Configuration.GetSection("AppSettings"));
            }
  2. 读取 AppSettingsOptions信息

    //通过依赖注入以下实例读取:
    IOptions<TOptions> //单例,不支持数据变化(重启更新),性能高
    IOptionsMonitor<TOptions> //单例,实时变更(侦听器OnChange)
    IOptionsSnapshot<TOptions>// 作用域注册,单次请求内不变
  3. 依赖注入
            //构造函数注入
            private readonly IOptionsMonitor<AppSettingsOptions> _settings;
            public DemoController(IOptionsMonitor<AppSettingsOptions> settings)
            {
                _settings= settings;
            }
            //参数注入方式 [FromServices]
            [HttpGet]
            public string Get([FromServices] IOptionsMonitor<AppSettingsOptions> settings)
            {
                return JsonSerializer.Serialize(settings.CurrentValue) ;
            }

     

 

赞(2)