NetCore配置文件使用全过程

299 阅读2分钟

这是我参与更文挑战的第14天,活动详情查看: 更文挑战

引言

本文主要针对在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的方法,经检验都可正常获取数据

  • _configuration[key]
  • _configuration.GetValue(key)

编码

[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);
}

输出结果