Asp .Net Core 讀取appsettings.json配置檔案

小世界的野孩子發表於2019-04-11
     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);


var a = GetAppsetting.getvalue.GetSettings.option1;//這樣我們就可以拿到配置檔案中GetSetting下面的option1的屬性值了
 
 

相關文章