.NET Core 如何获取环境变量?

How do environment variables get picked up with .NET Core?

我知道要使用 .NET Core 获取环境变量,理论上要使用的库 是 System.Environment 和方法 GetEnvironmentVariable("environmentVariableKeyHere")。但是,在 Linux (Ubuntu 18.04) 上,这并没有获取我基于用户的环境变量。我设置了变量 export THEVARIABLE="THEVALUE",.NET Core lib 库和方法不会选择它。我什至使用了 GetEnvironmentVariables() 方法并查看了它确实拾取的整个列表。该列表中的 None 个用户环境变量 where/are。

I 运行 在终端中通过 bash 和 boom 一个简单的 echo $THEVARIABLE,变量就在那里。该值按预期返回,但仍然没有通过 .NET 程序返回。说到这里,回购协议就在这里 > https://github.com/Adron/InteroperabilityBlackBox 如果你想检查一下。它是用 Rider + .NET Core 2.1 构建的,包括一个库(当 运行 尝试获取用户环境变量时,这是一个问题吗?)、控制台应用程序和测试库。

根据 docs:

On MacOS and Linux, the GetEnvironmentVariables method retrieves the name and value of all environment variables that are inherited from the parent process that launched the dotnet process or that are defined within the scope of the dotnet process itself. Once the dotnet process ends, these latter environment variables cease to exist.

.NET Core does not support per-machine or per-user environment variables.

看起来事情是在与 Jetbrains Rider 的用户会话之外执行的,我在这个代码和这个项目的初始开发中使用了它。从那以后,我想出了两个解决方案。第一,可以将环境变量添加到 Jetbrains Rider 中的大多数项目,以便它们在特定会话中执行和可用。如果使用 Visual Studio 代码或只是从 Bash 终端执行,那么用户会话的值当然可用。