zoukankan      html  css  js  c++  java
  • ASP.NET CORE 2.1 读取appsettings.json文件节点

    1:appsettings.json文件

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        "SqlServerConnection": "Data Source=127.0.0.1;Initial Catalog=test;User ID=sa;Password=sa0123"
      }
    }

    2:创建ConfigurationHelper类

     public static class ConfigurationHelper
        {
            /// <summary>
            ///  读取json文件
            /// </summary>
            /// <typeparam name="T">类型</typeparam>
            /// <param name="ParentKey">父级json节点</param>
            /// <param name="childrenKey">子级节点</param>
            /// <param name="path">appsettings.json</param>
            /// <returns></returns>
            public static object GetAppSettings<T>(string parentKey, string childrenKey = null, string path = "appsettings.json")
            {
                object strInfo = string.Empty;
                var builder = new ConfigurationBuilder().AddJsonFile(path);
                var configuration = builder.Build();
                try
                {
                    if (!string.IsNullOrWhiteSpace(childrenKey))
                    {
                        strInfo = configuration.GetSection(parentKey).GetValue<T>(childrenKey);
                    }
                    else
                    {
                        strInfo = configuration[parentKey].ToString();
                    }
                    return strInfo;
                }
                catch (Exception ex)
                {
                    //LogHelper.Error(ex.Message.ToString());
                    return null;
                }
            }
        }

    3:调用读取节点   

     (1):单独读取 AllowedHosts 节点

    var str = ConfigurationHelper.GetAppSettings<object>("AllowedHosts");

    (2):读取ConnectionString下面的SqlServerConnection的节点

     var str = ConfigurationHelper.GetAppSettings<object>("ConnectionStrings", "SqlServerConnection");
    或者
    var str = ConfigurationHelper.GetAppSettings<object>("ConnectionStrings:SqlServerConnection");

     

  • 相关阅读:
    disconf使用小结
    关于spring aop Advisor排序问题
    关于tomcat WEB-INF/lib下类加载顺序
    Netty5客户端源码解析
    巧用命令行工具 redis-cli
    redis学习总结
    聊聊Redis的持久化
    Git管理代码
    RabbitMQ连接池、生产者、消费者实例
    java处理节假日和工作时间的工具类
  • 原文地址:https://www.cnblogs.com/hbh123/p/11791601.html
Copyright © 2011-2022 走看看