ASP.NET CORE 2.1 File node reads appsettings.json

1: appsettings.json file

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

 

2: Create a class 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: Call read node   

 (1): reading individual node AllowedHosts

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

(2): reading the following SqlServerConnection node ConnectionString

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

 

Guess you like

Origin www.cnblogs.com/hbh123/p/11791601.html