zoukankan      html  css  js  c++  java
  • .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" });

  • 相关阅读:
    linux常用命令(4)rm命令
    Apache Commons 工具类
    Apache Commons 工具类介绍及简单使用
    linux常用命令(3)mkdir命令
    linux常用命令(2)pwd命令
    linux常用命令(1)cd命令
    小程序调用方法
    php用json_encode中文问题
    基于thinkphp的RBAC权限控制
    thinkphp获取ip地址及位置信息
  • 原文地址:https://www.cnblogs.com/Dark-Error/p/12726679.html
Copyright © 2011-2022 走看看