引言
本文主要针对在 NetCore 开发过程中对配置文件的操作进行一个使用说明,方便后期自己回顾。
配置文件使用的变化
从 NetCore 开始抛弃了 ASP.NET 默认使用 xml 配置文件 web.config 的方式 ,而是使用 appsetting.json 作为默认配置文件,使用 Configuration 库进行配置读取。
项目说明
首先,我们建立一个 CoreMvc 项目或者空 WebApi 项目
准备工作
项目的根目录下有一个 appsetting.json,默认内容如下
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*"}
复制代码
配置文件获取类【IConfiguration】已经默认依赖注入容器,使用构造函数注入即可
private readonly IConfiguration _configuration;
复制代码
编码
方法一 普通模式
开始编码进行读取内容的解析,首先建立一个控制器
列出俩种常用的获取 value 的方法,经检验都可正常获取数据
编码
[Route("config")]public class ConfigController : Controller{ private readonly IConfiguration _configuration;
public ConfigController(IConfiguration configuration) { _configuration = configuration; }
[HttpGet("GetConfig")] public IActionResult GetConfig() { string DefaultLevel = _configuration.GetSection("Logging").GetSection("LogLevel").GetSection("Default").Value; //使用key读取 string LifetimeLevel = _configuration["Logging:LogLevel:Lifetime"]; //使用GetValue<T> string MicrosoftLevel = _configuration.GetValue<string>("Logging:LogLevel:Microsoft"); string TestLevel = _configuration.GetValue<string>("Logging:LogLevel:Test", "Debug");
return new JsonResult(new { DefaultLevel, LifetimeLevel, MicrosoftLevel, TestLevel }); }}
复制代码
输出结果
{ "defaultLevel": "Information", "lifetimeLevel": "Warning", "microsoftLevel": "Warning", "testLevel": "Debug"}
复制代码
方法二 Option 模式
在某些情况下,我们需要在多场景中使用一个配置文件实体,使用上面的方面每一次都要重新获取,有没有一种方式支持直接注入一个配置实体呢?当然,option 模式便可以大展拳脚了。
在 appsetting.json 中新增内容如下,Person 代表依赖注入的配置实体
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "Person": { "Name": "张三", "Age": 10, "Desc": "描述" }}
复制代码
编码
首先在 configservice 中注入自定义的 Option。此处注意一下_configuration,需要被构造函数初始化
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration){ _configuration = configuration;}
复制代码
注入 option
services.Configure<PersonOption>(_configuration.GetSection("person"));
复制代码
控制器中注入并使用
private readonly IConfiguration _configuration;private readonly IOptions<PersonOption> _personOption;//采用这样的写法
public ConfigController(IConfiguration configuration, IOptions<PersonOption> personOption){ _configuration = configuration; _personOption = personOption;}
复制代码
[HttpGet("GetOptionConfig")]public IActionResult GetOptionConfig(){ var json = _personOption.Value; return new JsonResult(json);}
复制代码
输出结果
{ "name": "张三", "age": 10, "desc": "描述"}
复制代码
评论