Asp .Net Core 如何讀取appsettings.json配置文件?最近也有學習到如何讀取配置文件的,主要是通過 IConfiguration,以及在Program中初始化完成的。那麼今天給大家介紹下具體如何讀取配置文件的。 首先創建一個讀取配置文件的公共類GetAppsetting,我們 ...
Asp .Net Core 如何讀取appsettings.json配置文件?最近也有學習到如何讀取配置文件的,主要是通過 IConfiguration,以及在Program中初始化完成的。那麼今天給大家介紹下具體如何讀取配置文件的。 首先創建一個讀取配置文件的公共類GetAppsetting,我們可以看下此時配置文件中的內容
{ "GetSetting": { "option1": "value1_from_json", "option2": -1, "subsection": { "suboption1": "subvalue1_from_json", "suboption2": 200 } }, "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*" }在創建的GetAppsetting公共類中寫如下代碼
/// <summary> /// 實例化、調用GetAppsetting() /// </summary> /// <param name="builder"></param> public static void connection(IConfiguration build) { getvalue = new GetAppsetting(build); } /// <summary> /// 在類中進行連接 /// </summary> public static GetAppsetting getvalue { get; private set; } /// <summary> /// 最終實例化GetAppsetting(配置文件),讀取到GetSetting下麵的配置 /// </summary> /// <param name="builder"></param> public GetAppsetting(IConfigurationbuild) { this.GetSettings = new GetSetting(build.GetSection("GetSetting")); } public GetSetting GetSettings { get; } /// <summary> /// 獲取配置下麵的具體屬性的值 /// </summary> public class GetSetting { public string option1 { get; } public GetSetting(IConfiguration Configuration) { this.option1 = Configuration.GetSection("option1").Value; } }最後需要在Program中的Main函數中初始化
var Configuration = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) .Build(); GetAppsetting.connection(Configuration);參考:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2
var a = GetAppsetting.getvalue.GetSettings.option1;//這樣我們就可以拿到配置文件中GetSetting下麵的option1的屬性值了