将 appsettings 与 .NET Core 中的环境变量合并

Merging appsettings with environment variables in .NET Core

我正在 运行在 Docker(在 Kubernetes 中)中安装一个 .NET Core 应用程序,将环境变量传递给 Docker 容器并在我的应用程序中使用它们。

在我的 .NET Core 应用程序中,我有以下 C# class:

public class EnvironmentConfiguration
{
    public string EXAMPLE_SETTING { get; set; }
    public string MY_SETTING_2 { get; set; }
}

我这样设置 appsettings

config.
    AddJsonFile("appsettings.json").
    AddJsonFile($"appsettings.docker.json", true).
    AddEnvironmentVariables();  

DI 设置:

services.Configure<EnvironmentConfiguration>(Configuration);

在我的控制器中,我这样使用它:

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/my")]
public class MyController : Controller
{
    private readonly IOptions<EnvironmentConfiguration> _environmentConfiguration;

    public MyController(IOptions<EnvironmentConfiguration> environmentConfiguration)
    {
        _environmentConfiguration = environmentConfiguration;
    }
}       

我运行docker:

docker run -p 4000:5000 --env-file=myvariables

文件 myvariables 如下所示:

EXAMPLE_SETTING=example!!!
MY_SETTING_2=my-setting-2!!!!

这行得通。我可以使用我的 _environmentConfiguration 并查看我的变量是否已设置。

但是...我想将环境变量与 appsettings 合并,以便在找不到环境变量时将 appsettings 中的值用作后备。以某种方式合并这两行:

services.Configure<EnvironmentConfiguration>(settings => Configuration.GetSection("EnvironmentConfiguration").Bind(settings));
services.Configure<EnvironmentConfiguration>(Configuration);

这有可能吗?

我的后备计划是从 EnvironmentConfiguration class 继承并使用单独的 DI 注入两个单独的配置,然后在代码中合并它们 "manually" 但这种解决方案是不可取的.

config.
    AddJsonFile("appsettings.json").
    AddJsonFile("appsettings.docker.json", true).
    AddEnvironmentVariables();

实际上足以使用环境变量覆盖 appsettings 值。

假设您的 appsettings.json 文件中包含以下内容;

{
  "Logging": {
      "Level": "Debug"
  }
}

您可以通过将名为 Logging:Level 的环境变量设置为您偏好的值来覆盖 Logging.Level 的值。

请注意,: 用于在环境变量键中指定嵌套属性。

另请注意:来自docs

If a colon (:) can't be used in environment variable names on your system, replace the colon (:) with a double-underscore (__).