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

 

 

 

 

 

 

posted @ 2020-04-18 16:51  Dark丶潇洒哥  阅读(564)  评论(0编辑  收藏  举报