通过IConfiguration接口来读取实现代码
① 在appsettings.json文件加入配置信息
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Host": {
"Add": "127.0.0.5"
}
}
② 在使用的类通过构造函数注入过IConfiguration接口的实例
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
private readonly IConfiguration config;
//注入IConfiguration 实例
public WeatherForecastController(ILogger<WeatherForecastController> logger,IConfiguration config)
{
_logger = logger;
this.config = config;
}
[HttpGet]
public string Get()
{
//获取配置值
string hostAdd = config["Host:Add"];
_logger.LogInformation($"host addr is {hostAdd}");
return hostAdd;
}
}
使用选项模式绑定分层配置数据(官方推荐该模式)
① 在appsettings.json文件加入配置信息
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"HostInfo": {
"Add": "127.0.0.6",
"SSD": "20T"
}
}
② 创建选项类 HostInfo
选项类要求
必须是包含公共无参数构造函数的非抽象类。
类型的所有公共读写属性都已绑定。
不会绑定字段。 在上面的代码中,SectionName未绑定。 由于使用了 SectionName 属性,因此在将类绑定到配置提供程序时,不需要在应用中对字符串 "SectionName" 进行硬编码。
/// <summary>
/// 选项类
/// </summary>
public class HostInfo
{
public const string SectionName = "HostInfo";
public string Add { get; set; } = string.Empty;
public string SSD { get; set; } = string.Empty;
}
③ 读取配置文件
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
private readonly IConfiguration config;
public WeatherForecastController(ILogger<WeatherForecastController> logger,IConfiguration config)
{
_logger = logger;
this.config = config;
}
[HttpGet]
public string Get()
{
//获取配置值
HostInfo hostInfo = new HostInfo();
config.GetSection(HostInfo.SectionName).Bind(hostInfo);
return $"hostInfo.Add = {hostInfo.Add} ; hostInfo.SSD = {hostInfo.SSD}";
}
}
通过ConfigurationBinder.Get<T> 可能比使用 ConfigurationBinder.Bind 更方便。
HostInfo hostInfo = config.GetSection(HostInfo.SectionName).Get<HostInfo>();
使用选项模式时的替代方法是绑定HostInfo 部分并将它添加到依赖项注入服务容器。
① Startup类
public void ConfigureServices(IServiceCollection services)
{
//HostInfo被添加到了服务容器并已绑定到了配置
services.Configure<HostInfo>(Configuration.GetSection(HostInfo.SectionName));
services.AddControllers();
}
② 获取配置文件
public class WeatherForecastController : ControllerBase
{
private readonly IOptions<HostInfo> hostInfoOption;
/// <summary>
/// 通过构造函数获取绑定配置文件实例
/// </summary>
/// <param name="hostInfoOption"></param>
public WeatherForecastController(IOptions<HostInfo> hostInfoOption)
{
this.hostInfoOption = hostInfoOption;
}
[HttpGet]
public string Get()
{
//获取配置值
HostInfo hostInfo = hostInfoOption.Value;
return $"hostInfo.Add = {hostInfo.Add} ; hostInfo.SSD = {hostInfo.SSD}";
}
}