c# - 如何在 .NET 6.0 中构建 WebApplication 构建器之前访问配置变量?
问题描述
所以我的问题是,在 .NET 6 中构建构建器之前如何访问配置?
在 .NET 5 中,我们Startup.cs
分解为三个函数:
- 公共启动()
- 公共无效配置服务(IServiceCollection 服务)
- 公共无效配置(IApplicationBuilder 应用程序)
通过这个设置,我能够声明一个私有只读变量来存储和使用整个 Startup.cs 中的配置
private readonly IConfigurationRoot _config; // The variable in question.
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile($"appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
_config = builder.Build(); // Initializing the configuration to be access in ConfigureServices()
}
我会_config
在设置服务时经常使用该变量......例如:
// Example .NET 5 ConfigureServices.
services.AddSession(options =>
{
options.Cookie.Name = _config["Auth:AzureAd:SessionCookieName"];
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
但是,我知道在 .NET 6 中访问 Program.cs 中的配置的唯一方法是在创建 WebApplication 构建器之后var app = builder.Build();
问题是,您无法在构建构建器后修改服务。因此,在需要访问 appsettings/配置文件的这行代码之前,我拥有所有这些服务配置。
所以我的问题是,在 .NET 6 中构建构建器之前如何访问配置?
解决方案
推荐阅读
- jquery - 未选中任一复选框或脚本停止继续
- c# - 在 .net core 3.1 中强制对谓词构建器表达式进行客户端评估
- css - 我如何确保这在每台设备上看起来都一样?
- reactjs - React - 卡片不显示
- java - 如果定时器正在运行,则忽略扫描器输入,否则运行定时器 x 秒数(x = 扫描器输入)
- opc - 如何为 c++ sdk 更改 opc ua 中的 nodeid
- php - Laravel gmail 没有呈现我的邮件图片
- c# - 首先使用统一网格作为 ItemsPanel 列填充 ItemsControl
- javascript - Javascript:将数组中的对象相互比较一次
- python - 如何在正则表达式模式中使用反斜杠?