c# - .Net Core ConfigureAppConfiguration 添加额外的源覆盖环境特定设置
问题描述
在带有通用主机的 .NET Core 2.1 应用程序中使用 IConfigurationBuilder 时,我配置了 4 个源;但是在 ConfigureAppConfiguration 的范围之后有 6 个来源。
在某些时候,我已经加载的 2 个附加源以导致 appsettings.Environment.json 值被隐藏的顺序第二次添加。我还尝试删除 hostsettings.json 配置并验证这不会影响这一点。这适用于使用 WebjobsSDK 3.0 和 .Net Core 2.1 的 Azure Webjob
var builder = new HostBuilder()
.ConfigureHostConfiguration(configurationBuilder =>
{
//This is to do some basic host configuration and should only add 2 sources
configurationBuilder.SetBasePath(Directory.GetCurrentDirectory());
configurationBuilder.AddJsonFile("hostsettings.json", optional: true);
configurationBuilder.AddEnvironmentVariables(prefix: "APPSETTING_ASPNETCORE_");
})
.ConfigureAppConfiguration((hostContext, configurationBuilder) =>
{
//at this point there are 0 sources in the sources
IHostingEnvironment env = hostContext.HostingEnvironment;
configurationBuilder.SetBasePath(Directory.GetCurrentDirectory());
configurationBuilder.AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appSettings.{env.EnvironmentName}.json", optional: true,
reloadOnChange: true);
configurationBuilder.AddEnvironmentVariables(prefix: "APPSETTING_ASPNETCORE_");
//at this point there are 4 sources
})
.ConfigureServices((hostContext, servicesCollection) =>
{
//now there are 6, 2 additional source that are duplicates
servicesCollection.Configure<IConfiguration>(hostContext.Configuration);
})
我希望配置提供程序只有 4 个源,包括我已设置的 ChainedConfigSource。但是添加了 2 个额外的源,它们是 appsettings.json 和我在加载特定于环境的 appsettings.environment.json 之前声明的环境变量的副本。
现在,当注入一个类时,最后添加的 appsettings.json 设置通过 appsettings.environment.json 返回
解决方案
但是添加了 2 个额外的源,它们是
appsettings.json
和 环境变量的副本
我在使用 Azure WebJob 时遇到了类似的问题HostBuilder
,并注意到这两个源被附加到配置源列表的末尾。这产生了不希望的结果:开发设置appsettings.json
覆盖了appsettings.Production.json
.
这些额外的来源似乎是由 by在这里添加的ConfigureWebJobs
。
解决方法是重新排序HostBuilder
调用链,以便调用 toConfigureWebJobs
在调用to之前ConfigureAppConfiguration
。这两个额外的源仍然存在,但由于它们现在位于配置源列表的开头,而不是末尾,因此它们没有不良影响。
推荐阅读
- javascript - 基于另一个类的构造函数生成新类
- excel - 检查工作簿中的特定条件并计算结果
- javascript - 无法从脚本标签 HTML 中的 webpack bundle.js 导入模块
- javascript - 在 cookie 中保存用户决策
- ios - SwiftUI 和 Firestore 通信以显示不同的视图
- python - 如何用熊猫中前一列的前一行单元格填充一列的一些空单元格?
- github-actions - GitHub Action - Reviewdog - 422 验证失败
- ms-word - 将 huxtable 保存到 word 会丢失数字格式
- python - python中的pjsua make_call隐私和自定义标头
- r - 如何在 R 中一次重新编码具有相同映射的多个变量?