.NetCore類庫中訪問appsettings.json文件

首先在要使用appseting的類庫中使用nuget安裝包:Microsoft.Extensions.Configuration.Json

幫助類如下:

 public static class ConfigHelper
    {
        private static readonly IConfigurationRoot Configuration;
        static ConfigHelper()
        {
            Configuration = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();

        }
        public static T GetConfig<T>(string key, T defaultValue)
        {
            try
            {
                var result = Configuration[key];
                return (T)Convert.ChangeType(result, typeof(T));
            }
            catch (Exception)
            {
                if (defaultValue != null)
                {
                    return defaultValue;
                }
                return default(T);
            }
        }

        public static T GetConfig<T>(string key)
        {
            try
            {
                var result = Configuration[key];
                return (T)Convert.ChangeType(result, typeof(T));
            }
            catch (Exception)
            {
                throw new Exception(string.Format("沒有在配置文件中的appSettings中找到{0}的配置,請檢查配置文件配置!", key));
            }
        }
    }

比如在appsettings.json中的數據如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MyConn": "Server=10.18.193.200;Database=PagesMovie;uid=sa;pwd=Hello123!"
}

appsetting文件默認貌似不會複製到輸出目錄,所以需要修改一下

 

具體使用方法如下,比如要用MyConn的節點的值,

  string connectionString = Common.ConfigHelper.GetConfig<string>("MyConn");

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章