Asp .Net Core 如何读取appsettings.json配置文件?最近也有学习到如何读取配置文件的,主要是通过 IConfiguration,以及在Program中初始化完成的。那么今天给大家介绍下具体如何读取配置文件的。
首先创建一个读取配置文件的公共类GetAppsetting,我们可以看下此时配置文件中的内容
代码语言:javascript复制{
"GetSetting": {
"option1": "value1_from_json",
"option2": -1,
"subsection": {
"suboption1": "subvalue1_from_json",
"suboption2": 200
}
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
在创建的GetAppsetting公共类中写如下代码
代码语言:javascript复制 /// <summary>
/// 实例化、调用GetAppsetting()
/// </summary>
/// <param name="builder"></param>
public static void connection(IConfiguration build)
{
getvalue = new GetAppsetting(build);
}
/// <summary>
/// 在类中进行连接
/// </summary>
public static GetAppsetting getvalue { get; private set; }
/// <summary>
/// 最终实例化GetAppsetting(配置文件),读取到GetSetting下面的配置
/// </summary>
/// <param name="builder"></param>
public GetAppsetting(IConfigurationbuild)
{
this.GetSettings = new GetSetting(build.GetSection("GetSetting"));
}
public GetSetting GetSettings { get; }
/// <summary>
/// 获取配置下面的具体属性的值
/// </summary>
public class GetSetting
{
public string option1 { get; }
public GetSetting(IConfiguration Configuration)
{
this.option1 = Configuration.GetSection("option1").Value;
}
}
最后需要在Program中的Main函数中初始化
代码语言:javascript复制var Configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
GetAppsetting.connection(Configuration);
var a = GetAppsetting.getvalue.GetSettings.option1;//这样我们就可以拿到配置文件中GetSetting下面的option1的属性值了
参考:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2