.Net Core ConfigureAppConfiguration 添加覆盖环境特定设置的其他源

Rya*_*man 7 .net c# configuration azure-webjobssdk .net-core

在具有通用主机的 .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);
Run Code Online (Sandbox Code Playgroud)

})

我希望配置提供程序只有 4 个源,包括 ChainedConfigSource,我已经设置为包含在内。但是添加了 2 个额外的源,它们是 appsettings.json 和我在加载特定于环境的 appsettings.environment.json 之前声明的环境变量的副本。

现在,当注入类时,最后添加的 appsettings.json 设置通过 appsettings.environment.json 返回

Chr*_*eau 12

可以重新订购builder.Sources以满足您的需求。例如,下面是一个扩展方法,您可以使用它在最后一个文件之后而不是最后添加一个新的 JSON 文件:

public static class ConfigurationBuilderExtensions
{
  public static IConfigurationBuilder AddJsonFileAfterLastJsonFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange)
  {
    var jsonFileSource = new JsonConfigurationSource
    {
      FileProvider = null,
      Path = path,
      Optional = optional,
      ReloadOnChange = reloadOnChange
    };
    jsonFileSource.ResolveFileProvider();
    var lastJsonFileSource = builder.Sources.LastOrDefault(s => s is JsonConfigurationSource);
    var indexOfLastJsonFileSource = builder.Sources.IndexOf(lastJsonFileSource);
    builder.Sources.Insert(indexOfLastJsonFileSource == -1
      ? builder.Sources.Count
      : indexOfLastJsonFileSource + 1, jsonFileSource);
    return builder;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddJsonFileAfterLastJsonFile(
      "appsettings.Custom.json",
      optional: true,
      reloadOnChange: false);
})
Run Code Online (Sandbox Code Playgroud)

您可以根据自己的需要进行调整,并将其插入到任何需要的地方。


Ant*_*ony 7

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

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

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

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

  • 这让我发疯了 3 个小时。谢谢。现在找出为什么 .bind&lt;T&gt;() 默认为 appsettings.json 而不是 appsettings.{environment}.json 文件。 (4认同)

Fra*_*hes 6

2023 更新

请参阅示例 .net 7 应用程序。

首先清除所有配置源,然后根据需要进行设置。

// Program.cs

var builder = WebApplication.CreateBuilder(args);

// Clear Config sources
builder.Configuration.Sources.Clear();

// Add config sources from lowest priority to highest
builder.Configuration.AddJsonFile("mysettings.json");
builder.Configuration.AddEnvironmentVariables();

// Build and run app
var app = builder.Build();
app.MapGet("/", () => "Hello");
app.Run();
Run Code Online (Sandbox Code Playgroud)


Rya*_*man 4

因此,根据文档,WebHostBuilder 会为您加载 appSettings.json 和 appSettings.env.json 文件。但它也没有说明 HostBuilder 这样做,我相信这是由于缺乏文档,我无法确定源代码来自何处。

为了解决此问题,我更改了配置文件的设置方式。以前,我在 appSettings.json 文件和 appSettings.env.json 文件中都有连接字符串。因此,我在最后添加的配置文件替换基本配置文件中的值时遇到了问题。我现在已将基于环境的设置仅移至每个环境的配置文件中,并且仅将所有环境的全局设置保留在基本配置文件中。

.NET 框架配置转换设置的旧习惯似乎很难根除。我无法确定从多个提供程序声明的 IConfiguration 中的相同密钥是否应更改为最后加载的提供程序,我认为某些文档涵盖了这一点并确认了这一点,但现在我找不到它。