• .Net Core自定义读取配置文件信息appsettings.Json


    一、自定义读取配置文件信息appsettings.Json

      1.在Startup类配置

    1       public IConfiguration Configuration { get; }
    2         public IWebHostEnvironment Env { get; }
    3         public Startup(IConfiguration configuration, IWebHostEnvironment env)
    4         {
    5             Configuration = configuration;
    6             Env = env;
    7         }

      2.在Startup类的ConfigureServices配置

    services.AddSingleton(new Appsettings(Env.ContentRootPath));

      3.新建一个appsettings操作类

            static IConfiguration Configuration { get; set; }
    
            static string contentPath { get; set; }
    
            public Appsettings(string contentPath)
            {
                string Path = "appsettings.json";
    
                Configuration = new ConfigurationBuilder()
                   .SetBasePath(contentPath)
                   .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })
                   .Build();
            }
            /// <summary>
            /// 封装要操作的字符
            /// </summary>
            /// <param name="sections">节点配置</param>
            /// <returns></returns>
            public static string Get(params string[] sections)
            {
                try
                {
                    if (sections.Any())
                    {
                        return Configuration[string.Join(":", sections)];
                    }
                }
                catch (Exception) { }
    
                return "";
            }

      4.如何使用

     string test = appsettings.Get(new string[] { "test", "test1" });

  • 相关阅读:
    序列化和反序列化(2)[Serializable] 转
    http错误列表(转)
    公共Webservice
    序列化和反序列化(1)[Serializable]
    序列化中的[NonSerialized]字段 转
    后台调用前台js
    http的请求和响应过程2
    命名规则
    tsql LastIndexOf
    js产生随机数
  • 原文地址:https://www.cnblogs.com/Dark-Error/p/12726679.html
Copyright © 2020-2023  润新知