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及优先级排序
按照优先级排序:
- 命令行启动参数
- 无前缀的环境变量
- Development 环境中的 User secrets
- appsettings.{Environment}.json 文件,比如 appsettings.Production.json 或者 appsettings.Development.json
- 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