当前位置: 首页 > news >正文

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=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 optionalreloadOnChange: 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中配置:

{"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 ConfigurationConfiguration value for 'MyKey': @Configuration["MyKey"]

从 MVC Page中访问 Config

@using Microsoft.Extensions.Configuration
@inject IConfiguration ConfigurationConfiguration 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的优先级更高。

其他配置

  • launch.json/launchSettings.json ,用于开发环境。
  • web.config,是server配置文件。
http://www.lryc.cn/news/148539.html

相关文章:

  • MySql增量恢复
  • 设计模式--装饰者模式(Decorator Pattern)
  • Spring三级缓存解决循环依赖
  • Vscode自动移出不用的包
  • leetcode做题笔记120. 三角形最小路径和
  • weblogic/CVE-2018-2894文件上传漏洞复现
  • windows10默认浏览器总是自动更改为Edge浏览器
  • 系统架构设计师考试论文:论软件架构风格与应用
  • xss-labs靶场通关详解
  • 关于类和接口
  • 网络安全社区与资源分享: 推荐网络安全社区、论坛、博客、培训资源等,帮助从业者拓展人脉和知识。
  • SAP MM学习笔记26- SAP中 振替转记(转移过账)和 在库转送(库存转储)5 - 总结
  • Stable Diffusion WebUI提示词Prompts常用推荐
  • Android 13 Ethernet变更
  • 基于单片机的超声波语音测距系统
  • 算法系列-力扣876-求链表的中间节点
  • SpringBoot集成Redis、Redisson保姆教程【附源码】
  • c++多线程中常用的使用方法
  • 【dart】dart基础学习使用(一):变量、操作符、注释和库操作
  • element-plus 设置 el-date-picker 弹出框位置
  • C++day7(auto关键字、lambda表达式、C++中的数据类型转换、C++标准模板库(STL)、list、文件操作)
  • 纽扣电池/锂电池UN38.3安全检测报告
  • K8S:K8S自动化运维容器Docker集群
  • Java的guava 限流写法
  • [uniapp] scroll-view 简单实现 u-tabbar效果
  • vue常见问题汇总
  • GPT-3在化学中进行低数据发现是否足够?
  • gitlab升级
  • Matlab图像处理-灰度插值法
  • axios 或 fetch 如何实现对发出的请求的终止?