zoukankan      html  css  js  c++  java
  • 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里面就是你获取的配置文件的值

  • 相关阅读:
    [HEOI2013]Eden 的新背包问题
    [UOJ#77]A+B Problem
    [CodeForces]786B Legacy
    [LUOGU]P4098[HEOI2013]ALO
    [BZOJ3207]花神的嘲讽计划
    [LUOGU]P2633 Count on a tree
    【东莞市选2007】拦截导弹
    [JZOJ] 3462. 【NOIP2013模拟联考5】休息(rest)
    [BZOJ] 2705: [SDOI2012]Longge的问题
    [BZOJ] 1191: [HNOI2006]超级英雄Hero
  • 原文地址:https://www.cnblogs.com/wangyulong/p/9558701.html
Copyright © 2011-2022 走看看