zoukankan      html  css  js  c++  java
  • .net core 读取appsetting.json(一):Appsettings帮助类取值方法

    创建类Appsettings.cs

        /// <summary>
        /// appsettings.json操作类
        /// </summary>
        public class Appsettings
        {
            static IConfiguration Configuration { get; set; }
            static string contentPath { get; set; }
    
            public Appsettings(string contentPath)
            {
                string Path = "appsettings.json";
    
                //如果你把配置文件 是 根据环境变量来分开了,可以这样写
                //Path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json";
    
                Configuration = new ConfigurationBuilder()
                   .SetBasePath(contentPath)
                   .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })//这样的话,可以直接读目录里的json文件,而不是 bin 文件夹下的,所以不用修改复制属性
                   .Build();
    
    
            }
    
            /// <summary>
            /// 封装要操作的字符
            /// </summary>
            /// <param name="sections">节点配置</param>
            /// <returns></returns>
            public static string app(params string[] sections)
            {
                try
                {
    
                    if (sections.Any())
                    {
                        return Configuration[string.Join(":", sections)];
                    }
                }
                catch (Exception) { }
    
                return "";
            }
        }

    依赖注入IWebHostEnvironment 用来用去路径

            public IConfiguration Configuration { get; }
            public IWebHostEnvironment Env { get; }
            public Startup(IConfiguration configuration, IWebHostEnvironment env)
            {
                Configuration = configuration;
                Env = env;
            }

    注册Appsettings

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

    appsetting.json如下

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*",
      "Qny": {
        "qiniuyunAK": "AK", //ak
        "qiniuyunSK": "SK", //sk
        "qiniuyunBucket": "空间名称", 
        "prefixPath": "http://www.baidu.com" 
      }
    }

    使用取值

                Appsettings.app(new string[] { "Qny", "qiniuyunAK" });//AK
                Appsettings.app(new string[] { "Qny", "qiniuyunSK" });//SK
                Appsettings.app(new string[] { "Qny", "qiniuyunBucket" });//空间名称
                Appsettings.app(new string[] { "Qny", "prefixPath" }); //http://www.baidu.com
  • 相关阅读:
    HashMap的put方法
    死锁相关
    AVL树
    xss漏洞
    hash
    古典密码学教学
    python | 实现控制多台机器的脚本
    python | 端口扫描器(多线程)
    每日一洞 | 细说渗透江湖之出荆棘入深林
    每日一洞 | 细说渗透江湖之柳暗花明又一村
  • 原文地址:https://www.cnblogs.com/mi21/p/12212657.html
Copyright © 2011-2022 走看看