首页 > 解决方案 > .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 返回

标签: c#.netconfiguration.net-coreazure-webjobssdk

解决方案


但是添加了 2 个额外的源,它们是appsettings.json和 环境变量的副本

我在使用 Azure WebJob 时遇到了类似的问题HostBuilder,并注意到这两个源被附加到配置源列表的末尾。这产生了不希望的结果:开发设置appsettings.json覆盖了appsettings.Production.json.

这些额外的来源似乎是由 by在这里添加的ConfigureWebJobs

解决方法是重新排序HostBuilder调用链,以便调用 toConfigureWebJobs在调用to之前ConfigureAppConfiguration。这两个额外的源仍然存在,但由于它们现在位于配置源列表的开头,而不是末尾,因此它们没有不良影响。


推荐阅读