Asp .Net Core 读取appsettings.json配置文件

     Asp .Net Core 如何读取appsettings.json配置文件?最近也有学习到如何读取配置文件的,主要是通过 IConfiguration,以及在Program中初始化完成的。那么今天给大家介绍下具体如何读取配置文件的。
 
首先创建一个读取配置文件的公共类GetAppsetting,我们可以看下此时配置文件中的内容
{
"GetSetting": {
"option1": "value1_from_json",
"option2": -,
"subsection": {
"suboption1": "subvalue1_from_json",
"suboption2":
}
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
 
 
在创建的GetAppsetting公共类中写如下代码
   /// <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函数中初始化
var Configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
GetAppsetting.connection(Configuration); var a = GetAppsetting.getvalue.GetSettings.option1;//这样我们就可以拿到配置文件中GetSetting下面的option1的属性值了
 
 
 
 

欢迎大家扫描下方二维码,和我一起学习更多的知识

上一篇:HDU1814 Peaceful Commission 2-sat


下一篇:IBatis.Net学习笔记七--日志处理