ASP.NET Core 8 的配置类 Configuration

Configuration

Configuration 可以从两个途径设置:

  • WebApplication创建的对象app.Configuration 属性
  • WebApplicationBuilder 创建的 builder.Configuration 属性

app的Configuration优先级更高,host Configuration作为替补配置,因为app运行在host之上。
每种方式都提供了非常丰富的配置选择,可用于各种场景,以便在开发环境和产品环境时使用。

Host 预设的变量

这些变量在初始化builder的时候,就预设了:

  • Application 名称
  • Environment 名称, 比如 Development, Production, and Staging
  • Content 根目录
  • Web 根目录
  • 标识是否扫描启动要用的DLL
  • App 和 IHostBuilder.ConfigureAppConfiguration 回调中的HostBuilderContext.Configuration 的代码要读取的变量

其他host的设置项都从 App 的Configuration 读取,而不是从host的Configuration 读取。
只有在App 的Configuration 中没有设置的情况下,才从host的Configuration 读取。

Application configuration 的provider及优先级排序

按照优先级排序:

  1. 命令行启动参数
  2. 无前缀的环境变量
  3. Development 环境中的 User secrets
  4. appsettings.{Environment}.json 文件,比如 appsettings.Production.json 或者 appsettings.Development.json
  5. appsettings.json 文件

引入这些provider的顺序与它们的优先级相反,下面从低到高介绍各个provider:

appsettings.json 文件的例子

{
   
  "Position": {
   
    "Title": "Editor",
    "Name": "Joe Smith"
  },
  "MyKey": "My appsettings.json Value",
  "Logging": {
   
    "LogLevel": {
   
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

可以这样读取:

var myKeyValue = Configuration["MyKey"];
var name = Configuration["Position:Name"];
var defaultLogLevel = Configuration["Logging:LogLevel:Default"];

User Secret

无前缀的环境变量

无前缀的环境变量是不带 ASPNETCORE_ 或者 DOTNET_ 前缀的环境变量,
比如 launchSettings.json 文件中的 “ASPNETCORE_ENVIRONMENT”: “Development”。

可以通过代码:

builder.Configuration.AddEnvironmentVariables(prefix: "MyCustomPrefix_");

或者命令行:

setx MyKey "My key from setx Environment" /M
setx Position__Title Environment_Editor /M
setx Position__Name Environment_Rick /M

来设置。

launchSettings.json 中的 环境变量

launchSettings.json 中的 环境变量会覆盖上面设置的系统变量:

"applicationUrl": "https://localhost:5001;http://localhost:5000"

遍历所有环境变量

以便debug。

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
foreach (var c in builder.Configuration.AsEnumerable())
{
   
    Console.WriteLine(c.Key + " = " + c.Value);
}

命令行启动参数

如:

dotnet run MyKey="Using =" Position:Title=Cmd Position:Name
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值