欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-17 08:33:49
一、自定义读取配置文件信息appsettings.Json 1.在Startup类配置 1 public IConfiguration Configuration { get; } 2 public IWebHostEnvironment Env { get; } 3 public Startup( ......

一、自定义读取配置文件信息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" });

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

 

 

 

 

 

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