首先在要使用appseting的类库中使用nuget安装包:Microsoft.Extensions.Configuration.Json
帮助类如下:
public static class ConfigHelper
{
private static readonly IConfigurationRoot Configuration;
static ConfigHelper()
{
Configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
}
public static T GetConfig<T>(string key, T defaultValue)
{
try
{
var result = Configuration[key];
return (T)Convert.ChangeType(result, typeof(T));
}
catch (Exception)
{
if (defaultValue != null)
{
return defaultValue;
}
return default(T);
}
}
public static T GetConfig<T>(string key)
{
try
{
var result = Configuration[key];
return (T)Convert.ChangeType(result, typeof(T));
}
catch (Exception)
{
throw new Exception(string.Format("没有在配置文件中的appSettings中找到{0}的配置,请检查配置文件配置!", key));
}
}
}
比如在appsettings.json中的数据如下:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"MyConn": "Server=10.18.193.200;Database=PagesMovie;uid=sa;pwd=Hello123!"
}
appsetting文件默认貌似不会复制到输出目录,所以需要修改一下
具体使用方法如下,比如要用MyConn的节点的值,
string connectionString = Common.ConfigHelper.GetConfig<string>("MyConn");