一、创建项目
1、创建一个NETCore5.0的Web API项目。
2、appsetting.json
中的内容如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"SchoolName": "咸鱼一中",
"Student": {
"ClassName": "高一一班",
"StudentList": [
"张三",
"李四",
"王五"
]
}
}
二、配置文件读取方式一
通过**IConfiguration[参数名称]**方式读取appsetting.json
中的配置信息。
start.up中输出配置文件信息
1、通过startup.cs
构造函数注入IConfiguration
2、startup.cs
中的代码如下:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
Console.WriteLine("SchoolName:"+Configuration["SchoolName"]);
//寻找某个对象的子对象,则获取方式为"当前对象:子对象"
Console.WriteLine("ClassName:" + Configuration["Student:ClassName"]);
//寻找某个数组对象指定下标值得方式为"数组:下标"
Console.WriteLine("StudentList[0]:" + Configuration["Student:StudentList:0"]);
Console.WriteLine("StudentList[1]:" + Configuration["Student:StudentList:1"]);
Console.WriteLine("StudentList[2]:" + Configuration["Student:StudentList:2"]);
}
//省略Configure()
3、运行项目,可看到控制台中依次输出appsetting.json
中想应的内容:
控制器中输出配置文件信息
1、通过startup.cs
构造函数注入IConfiguration
2、具体代码如下:
private readonly IConfiguration _configuration;
public WeatherForecastController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet]
[Route("GetConfig")]
public string GetConfig()
{
return $"SchoolName:{_configuration["SchoolName"]}\n" +
$"ClassName:{_configuration["Student:ClassName"]}\n" +
$"StudentList[0]:{_configuration["Student:StudentList:0"]}\n" +
$"StudentList[1]:{_configuration["Student:StudentList:1"]}\n"+
$"StudentList[2]:{_configuration["Student:StudentList:2"]}\n";
}
3、浏览器中访问"https://localhost:5001/Weatherforecast/GetConfig",可看到正确输出appsetting.json
中对应的配置文件信息。
三、配置文件读取方式二
1、创建一个名为StudentOptions
的实体类,代码如下:
public class StudentOptions
{
/// <summary>
/// 班级名
/// </summary>
public string ClassName { get; set; }
public List<string> StudentList { get; set; }
}
2、startup.cs
中的添加代码如下:
public void ConfigureServices(IServiceCollection services)
{
//省略其他代码
//将配置文件中的数据映射到实体类
services.Configure<StudentOptions>(Configuration.GetSection("Student"));
}
3、控制器中的代码如下:
private readonly IConfiguration _configuration;
private readonly StudentOptions _studentOptions;
public WeatherForecastController(IConfiguration configuration, IOptions<StudentOptions> options)
{
_configuration = configuration;
_studentOptions = options.Value;
}
[HttpGet]
[Route("GetConfigByEntity")]
public string GetConfigByEntity()
{
return JsonConvert.SerializeObject(_studentOptions);
}
4、浏览器中访问"https://localhost:5001/Weatherforecast/GetConfigByEntity",可看到正确输出appsetting.json
中对应的Student配置文件信息
四、源码
https://gitee.com/wusuoweixgy/NET5Code/tree/master/ConfigReadWebApp