.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");

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值