Configuration 可以从两个途径设置:
app的Configuration优先级更高,host Configuration作为替补配置,因为app运行在host之上。
每种方式都提供了非常丰富的配置选择,可用于各种场景,以便在开发环境和产品环境时使用。
这些变量在初始化builder的时候,就预设了:
其他host的设置项都从 App 的Configuration 读取,而不是从host的Configuration 读取。
只有在App 的Configuration 中没有设置的情况下,才从host的Configuration 读取。
按照优先级排序:
引入这些provider的顺序与它们的优先级相反,下面从低到高介绍各个provider:
{
"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"];
无前缀的环境变量是不带 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 中的 环境变量会覆盖上面设置的系统变量:
"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=Cmd_Rick
还可以预设一下mapping,将短的启动参数映射到原有的长参数名上:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var switchMappings = new Dictionary<string, string>()
{
{ "-k1", "key1" },
{ "-k2", "key2" },
{ "--alt3", "key3" },
{ "--alt4", "key4" },
{ "--alt5", "key5" },
{ "--alt6", "key6" },
};
builder.Configuration.AddCommandLine(args, switchMappings);
var app = builder.Build();
然后当用命令行时:
dotnet run -k1 value1 -k2 value2 --alt3=value2 /alt4=value3 --alt5 value5 /alt6 value6
-k1 的值就被映射到key1上了。
也可以通过Visual Studio的Debug窗口设置启动参数。
当在环境变量中发现这些前缀的变量时,前缀会被去掉,然后数据库的连接字符串会自动改成:
MYSQLCONNSTR_{KEY} --> ConnectionStrings:{KEY}
然后通过config可以读取到 数据库provider,自宝义provider则没有 数据库provider:
key: ConnectionStrings:{KEY}_ProviderName
value: MySql.Data.MySqlClient
var builder = WebApplication.CreateBuilder(args);
builder.Configuration
.AddIniFile("MyIniConfig.ini", optional: true, reloadOnChange: true)
.AddIniFile($"MyIniConfig.{builder.Environment.EnvironmentName}.ini",
optional: true, reloadOnChange: true);
builder.Configuration.AddEnvironmentVariables();
builder.Configuration.AddCommandLine(args);
builder.Services.AddRazorPages();
var app = builder.Build();
INI文件的例子:
MyKey="MyIniConfig.ini Value"
[Position]
Title="My INI Config title"
Name="My INI Config name"
[Logging:LogLevel]
Default=Information
Microsoft=Warning
using Microsoft.Extensions.DependencyInjection.ConfigSample.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("MyConfig.json",
optional: true, //The file is optional
reloadOnChange: true); //The file is reloaded when changes are saved
builder.Services.AddRazorPages();
var app = builder.Build();
一般用不到JSON 配置provider
var builder = WebApplication.CreateBuilder(args);
builder. Configuration
.AddXmlFile("MyXMLFile.xml", optional: true, reloadOnChange: true)
.AddXmlFile($"MyXMLFile.{builder.Environment.EnvironmentName}.xml",
optional: true, reloadOnChange: true);
builder.Configuration.AddEnvironmentVariables();
builder.Configuration.AddCommandLine(args);
builder.Services.AddRazorPages();
var app = builder. Build();
XML文件的例子:
<configuration>
<MyKey>MyXMLFile ValueMyKey>
<Position>
<Title>Title from MyXMLFileTitle>
<Name>Name from MyXMLFileName>
Position>
<Logging>
<LogLevel>
<Default>InformationDefault>
<Microsoft>WarningMicrosoft>
LogLevel>
Logging>
configuration>
用于docker,使用一个目录中的文件作为配置。key是文件名,value是文件内容。
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
var path = Path.Combine(
Directory.GetCurrentDirectory(), "path/to/files");
config.AddKeyPerFile(directoryPath: path, optional: true);
})
var builder = WebApplication.CreateBuilder(args);
var Dict = new Dictionary<string, string>
{
{"MyKey", "Dictionary MyKey Value"},
{"Position:Title", "Dictionary_Title"},
{"Position:Name", "Dictionary_Name" },
{"Logging:LogLevel:Default", "Warning"}
};
builder.Configuration.AddInMemoryCollection(Dict);
builder.Configuration.AddEnvironmentVariables();
builder.Configuration.AddCommandLine(args);
builder.Services.AddRazorPages();
var app = builder.Build();
可以在appsettings.json中配置:
{
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://localhost:9999"
}
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
public class Service
{
private readonly IConfiguration _config;
public Service(IConfiguration config) =>
_config = config;
public void DoSomething()
{
var configSettingValue = _config["ConfigSetting"];
// ...
}
}
@page
@model Test5Model
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
Configuration value for 'MyKey': @Configuration["MyKey"]
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
Configuration value for 'MyKey': @Configuration["MyKey"]
var builder = WebApplication.CreateBuilder(args);
var key1 = builder.Configuration.GetValue<string>("KeyOne");
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
var key2 = app.Configuration.GetValue<int>("KeyTwo");
var key3 = app.Configuration.GetValue<bool>("KeyThree");
app.Logger.LogInformation("KeyOne: {KeyOne}", key1);
app.Logger.LogInformation("KeyTwo: {KeyTwo}", key2);
app.Logger.LogInformation("KeyThree: {KeyThree}", key3);
app.Run();
在启动和配置App前,Host 先被配置,并先被启动。
然后Host负责启动 App 和 App的生命周期管理。
App和Host 都用上面提到的各种provider。
Host configuration也会包含在App configuration,但是App configuration的优先级更高。