NETCore 读取JSON配置文件
AppSetting.json


{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Title": "Hello World!",
"Message": "Hello World - AppSetting - 啊!",
"ConnectionStrings": {
"Mysql": "server=localhost;port=3306;userid=root;pwd=123456;database=testefdb",
"MsSql": "Data Source=.;Initial Catalog=testefdb;User Id=root;Password=123456;"
}
}
appsetting.json
jsconfig.json


{
"Name": "Joker",
"Sex": "Man",
"Describe": "描述",
"Message": "Hello World - JsConfig - 啊!"
}
jsconfig.json
构造函数注入参数
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
获取配置文件参数
1.获取指定key的值
var title = Configuration["Title"]; var mysql = Configuration["ConnectionStrings:Mysql"];
2.绑定配置模型对象
// 获取所有配置
var appSetting = new MyAppSetting();
Configuration.Bind(appSetting);
var loggerDefault = appSetting.Logging.LogLevel.Default;
// 获取指定节点配置
var connectionstrings = new Connectionstrings();
Configuration.GetSection("ConnectionStrings").Bind(connectionstrings);
var mssql = connectionstrings.MsSql;
3.注册配置选项的服务
3.1.在 Startup/ConfigureServices 注册配置选项服务
// 注册配置选项服务
services.Configure<MyAppSetting>(Configuration);
// 注册 自定义配置信息
var config = new ConfigurationBuilder().AddJsonFile("jsconfig.json", true, true).Build();
var name = config["Name"];
services.Configure<MyJsConfig>(config);
3.2.在 Startup/Configure 获取配置
public void Configure(IOptions<MyAppSetting> appSettingOptions, IOptionsSnapshot<MyJsConfig> myJsConfigoptions)
{
// 读取 配置信息【appsettings.json】
var loggerMicrosoft = appSettingOptions.Value.Logging.LogLevel.Microsoft;
// 读取 自定义配置信息【jsconfig.json】
var describe = myJsConfigoptions.Value.Describe;
}
*注:
1.在 Startup/ConfigureServices 通过 AddJsonFile 注册自定义配置信息,使用IOptionsSnapshot【站点启动后,每次获取到的值都是配置文件里的最新值】没有效果,需要在 Program/CreateHostBuilder 中进行配置【有知道的大佬求解释】
public static IHostBuilder CreateHostBuilder(string[] args)
{
// 创建默认Builder,完成各种基础配置: Host.CreateDefaultBuilder 已注册 appsetting.json
IHostBuilder hostBuild = Host.CreateDefaultBuilder(args);
// 配置默认WebHost
hostBuild.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
hostBuild.ConfigureAppConfiguration(configBuilder =>
{
// 注册 自定义配置信息,reloadOnChange:如果文件更改,是否应重新加载配置
configBuilder.AddJsonFile("jsconfig.json", true, reloadOnChange: true);
});
return hostBuild;
}
2.appsetting.json 和 jsconfig.json 两个配置文件会同时生效,同名的值后者优先【jsconfig.json】
3.早期Core版本获取动态配置需要手动指定 reloadOnchange = true,目前3.1已默认配置,只需要使用 Microsoft.Extensions.Options.IOptionsSnapshot 就可以
赞 (0)
