Fork me on GitHub

NetCore读取配置文件

1、添加一个Json配置文件,名称随意,这里暂定名称为xxx.json,配置文件里面添加一个Json对象,例如

{
  "AwardSetting": {
    "ServiceFeeProportion": 0.01,
    "ExtractProportion": 0.09,
    "ExtractReceiveAddress": ""
  }
}

2、添加一个类,名称要和定义的Json对象定义的一致,例如

namespace Example.Award
{
    public class AwardSetting
    {
        public double ServiceFeeProportion { get; set; }

        public double ExtractProportion { get; set; }

        public string ExtractReceiveAddress { get; set; }
    }
}

3、配置解析类,注意引入Microsoft.Extensions.Options.ConfigurationExtensions包, 注意using的包

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace FiiiChain.MiningPool.Award.Tools
{
    public class ConfigurationTool
    {
        public T GetAppSettings<T>(string key) where T : class, new()
        {
            IConfiguration config = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "xxx.json", ReloadOnChange = true })
            .Build();

            T appconfig = new ServiceCollection()
                .AddOptions()
                .Configure<T>(config.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;

            return appconfig;
        }
    }
}

4、在调用的地方

ConfigurationTool tool = new ConfigurationTool();
AwardSetting setting = tool.GetAppSettings<AwardSetting>("AwardSetting");

如果不出意外的话setting里面就是你获取的配置文件的值

posted @ 2018-08-30 10:39 雪山玉龙 阅读(...) 评论(...) 编辑 收藏