NETCore⼊门系列(读取appsetting.json配置⽂件内容)⽂章⽬录
⼀、创建项⽬
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、浏览器中访问"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、浏览器中访问"localhost:5001/Weatherforecast/GetConfigByEntity",可看到正确输出appsetting.json中对应的Student 配置⽂件信息
四、源码
发布评论