Asp.net core中的配置提供程序和读取

ASP.NET Core 中的应用程序配置是使用一个或多个配置提供程序执行的。 配置提供程序使用各种配置源从键值对读取配置数据:

  • 设置文件,例如 appsettings.json
  • 环境变量
  • Azure Key Vault
  • Azure 应用程序配置
  • 命令行参数
  • 已安装或已创建的自定义提供程序
  • 目录文件
  • 内存中的 .NET 对象

配置提供

文件配置提供

这里只讲一种json配置,在program.cs下进行配置:

builder.Configuration.AddJsonFile("MyConfig.json",
        optional: true,
        reloadOnChange: true);

optional:这个参数表示文件是否可选,框架启动时会检查文件,false会在检查不到文件时报错,true会在找不到文件时给一个默认值。

reloadOnChange:更改后会重新加载文件

内存配置提供

var Dict = new Dictionary<string, string>
        {
           {"Key", "Value"},
           {"Logging:LogLevel:Default", "Information"}
        };

builder.Configuration.AddInMemoryCollection(Dict);

命令行配置提供

builder.Configuration.AddCommandLine(args);
>dotnet run --Key Value

环境变量配置提供

builder.Configuration.AddEnvironmentVariables();

配置读取

索引器

[ApiController]
[Route("[controller]/[action]")]
public class MyController : ControllerBase
{
    private readonly IConfiguration _configuration;

    public MyController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [HttpGet]
    public void Test()
    {
        var value = _configuration["Key"];
    }
}

但是直接使用索引器读取配置,可能会有一些类型转换的问题,所以一般不推荐这种方式

ConfigurationBinder 静态方法

//GetValue:读取int型配置值,找不到使用默认值1
_configuration.GetValue<int>("Key", 1); 

//GetSection:直接读取部分节点
_configuration.GetSection("Logging:LogLevel");

//Get:配置绑定到对象
_configuration.GetSection("Logging:LogLevel").Get<Level>();

//Bind:与get类似,单直接绑定实例
_configuration.GetSection("Logging:LogLevel").Bind(level);

选项模式选项接口

前面的Get和Bind就是一种选项模式应用,绑定的类称为选项类,这里介绍另一种选项模式用法,

这里需要先在依赖注入容器中注册:

builder.Services.AddOptions().Configure<TestOptions>(builder.Configuration.GetSection(TestOptions.Test));

选项接口主要有:

  • IOptions
  • IOptionsMonitor
  • IOptionsSnapshot

三者的不同可以简单理解为Singleton,Transcient,Scoped。一般推荐使用IOptionsSnapshot,使得配置可以动态更新,但在同一次请求中不变:

private readonly IOptionsSnapshot<TestOptions> _testOption;

public MyController(IOptionsSnapshot<TestOptions> testOption)
{
    _testOption = testOption;
}

[HttpGet]
public void Test()
{
    var value = _testOption.Value.Key;
}
posted @   shanawdj  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示