AppSetting.json { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "Allow ...
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 就可以