一、在appsettings.json中增加属性字段:app。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"app": {
"id": "1",
"name": "名称"
}
}
二、在Program.cs中读取
string id = builder.Configuration.GetSection("app")["id"];
string name = builder.Configuration.GetSection("app")["name"];
三、在控制器中读取
首先改造构造函数,形参增加IConfiguration。
private readonly ILogger<WeatherForecastController> _logger;
private IConfiguration Configuration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
_logger = logger;
this.Configuration = configuration;
}
在方法中读取:
string id = Configuration.GetSection("app")["id"];
string name = Configuration.GetSection("app")["name"];
//或
string id2= Configuration["app:id"];
string name2 = Configuration["app:name"];
四、直接序列化为对象
定义类appModel:
public class appModel
{
public string id { get; set; }
public string name { get; set; }
}
在Program.cs中读取
//使用Get序列化成为对象
appModel appModel = builder.Configuration.GetSection("app").Get<appModel>();
//或者使用bind函数
appModel appModel1 = new appModel();
builder.Configuration.GetSection("app").Bind(appModel1);
我已将代码上传,下载码是:583B8232C0
下载码是啥?如何下载=》点击查看