首页 > 解决方案 > DotNetCore 3.1 中配置的双下划线似乎不像我预期的那样工作

问题描述

我正在尝试为在 ASP.Net core 3.1 中工作的配置添加双下划线,如下所述:https ://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?tabs=basicconfiguration&view=aspnetcore -3.1#环境变量

我已经为手动执行此操作的配置编写了一些代码

  1. 检查环境变量
  2. 检查 AppSettings...json 文件

但我看到在 .net 3.1 中,默认情况下应该支持这一点,但需要注意的是 unix 平台上的分层设置。在这种情况下,您不能使用此语法

Configuration["SomeSection:SomeConfig"]

解决这个环境变量

## Environment Var
SomeConfig:SomeConfig

因为 linux 不支持 Env Var 名称中的冒号。但是,如果将代码部署到 Windows 机器上,这将起作用。因此,.net 似乎表明您可以使用这种语法

Configuration["SomeSection__SomeConfig"]

这将解决以下任何配置

// AppSettings...json
{
   "SomeSection" {
      "SomeConfig": "some value"
   }
}

或者

# Environment Var on linux
SomeConfig__SomeConfig

或者

// Environment Var on windows
SomeConfig:SomeConfig

有谁知道我做错了什么?

编辑:请注意,我知道这个问题的答案,如果重新打开它,我会很乐意回答。

标签: asp.net-core.net-core

解决方案


我很想念了解文档。它的工作方式是如果你在你的start.cs

Configuration["SomeSection:SomeConfig"]

它会正确解决

// AppSettings...json
{
   "SomeSection" {
      "SomeConfig": "some value"
   }
}

从您的各种 AppSettings 文件中。

SomeSection:SomeConfig但是,如果您使用将使用的名称而不是 AppSettings 值定义环境变量,这是一个很棒的功能。在 docker 容器中运行应用程序时,这通常是可取的。

但是,如果在 linux 操作系统上,则无法创建名称为 的环境变量SomeSection:SomeConfig。因此,如果您在 linux 机器或 linux 容器中,如果您SomeSection__SomeConfig使用__(双下划线)而不是 a命名环境变量,:那么它将由

Configuration["SomeSection:SomeConfig"]

推荐阅读