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=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窗口设置启动参数。
数据库连接前缀
- CUSTOMCONNSTR_ :自宝义provider
- MYSQLCONNSTR_ MySQLprovider
- SQLAZURECONNSTR_ :Azure SQL Database
- SQLCONNSTR_ :SQL Serverprovider
当在环境变量中发现这些前缀的变量时,前缀会被去掉,然后数据库的连接字符串会自动改成:
MYSQLCONNSTR_{KEY} --> ConnectionStrings:{KEY}
然后通过config可以读取到 数据库provider,自宝义provider则没有 数据库provider:
key: ConnectionStrings:{KEY}_ProviderName
value: MySql.Data.MySqlClient
文件型配置的Provider
- INI 配置 provider
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
- JSON 配置provider
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
- XML 配置 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文件的例子:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<MyKey>MyXMLFile Value</MyKey>
<Position>
<Title>Title from MyXMLFile</Title>
<Name>Name from MyXMLFile</Name>
</Position>
<Logging>
<LogLevel>
<Default>Information</Default>
<Microsoft>Warning</Microsoft>
</LogLevel>
</Logging>
</configuration>
Key-per-file 配置 provider
用于docker,使用一个目录中的文件作为配置。key是文件名,value是文件内容。
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
var path = Path.Combine(
Directory.GetCurrentDirectory(), "path/to/files");
config.AddKeyPerFile(directoryPath: path, optional: true);
})
内存配置 Provider
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();
配置Kestrel 的 EndPoint
可以在appsettings.json中配置:文章来源:https://www.toymoban.com/news/detail-679439.html
{
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://localhost:9999"
}
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
从依赖注入访问Config
public class Service
{
private readonly IConfiguration _config;
public Service(IConfiguration config) =>
_config = config;
public void DoSomething()
{
var configSettingValue = _config["ConfigSetting"];
// ...
}
}
从Razor Pages中访问Config
@page
@model Test5Model
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
Configuration value for 'MyKey': @Configuration["MyKey"]
从 MVC Page中访问 Config
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
Configuration value for 'MyKey': @Configuration["MyKey"]
从Main函数中访问
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();
Host configuration vs App configuration
在启动和配置App前,Host 先被配置,并先被启动。
然后Host负责启动 App 和 App的生命周期管理。
App和Host 都用上面提到的各种provider。
Host configuration也会包含在App configuration,但是App configuration的优先级更高。文章来源地址https://www.toymoban.com/news/detail-679439.html
其他配置
- launch.json/launchSettings.json ,用于开发环境。
- web.config,是server配置文件。
到了这里,关于ASP.NET Core 8 的配置类 Configuration的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!