NetCore讀取配置文件

一、添加一個Json配置文件,名稱隨意,這裏暫定名稱爲xxx.json,配置文件裏面添加一個Json對象,例如json

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

二、添加一個類,名稱要和定義的Json對象定義的一致,例如app

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

        public double ExtractProportion { get; set; }

        public string ExtractReceiveAddress { get; set; }
    }
}

三、配置解析類,注意引入Microsoft.Extensions.Options.ConfigurationExtensions包, 注意using的包ide

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;
        }
    }
}

四、在調用的地方ui

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

若是不出意外的話setting裏面就是你獲取的配置文件的值spa

相關文章
相關標籤/搜索