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");