Visual Studio 2022 System.Environment.GetEnvironmentVariable 不工作

Visual Studio 2022 System.Environment.GetEnvironmentVariable not working

我知道这仍处于预览阶段,但我只是想确保我没有做错任何事,因为我过去曾做过类似的事情。我在属性中设置了环境变量:

我正在尝试设置我的测试:

[TestInitialize]
public void Initialize()
{
    var test = Environment.GetEnvironmentVariables();
    // test enumerates all the Env variables, don't see it there
    var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING");
    if (string.IsNullOrWhiteSpace(connectionString)) // so this is obviously null
        throw new ArgumentNullException("CONNECTION_STRING");
    _ConnectionString = connectionString;
}

从我的评论可以看出,环境变量不是found/loaded。

我错过了什么?谢谢。

我假设您使用的是 Visual Studio 2022,因为您使用的是 .NET 6 和最小主机(即没有 Startup.cs)?

一般偏好不将信息存储在环境变量中,因为此信息经常上传到 GitHub 并且可以被拖网并用来对付你。

对于本地开发机密,首选是使用 secrets.json 文件存储这些内容。 Safe Storage of Secrets, as well as details on accessing Configuration files at .

中提供了有关如何执行此操作的信息

对于 TL;DR: Crowd 以下步骤可能会有所帮助(这是我在 .NET 6 的 Blazor 应用程序中所做的):

  1. 在Visual Studio2022年,右击有问题的项目,然后select'Manage User Secrets'。这将创建一个本地 secrets.json 文件并打开它。它还会在 UserSecretsId.
  2. 的项目磁贴中添加一个 GUID
  3. 像创建环境变量一样,在此文件中将您的机密创建为 JSON 键值对。
  4. 转到项目中的 'Connected Services' 并配置 Secrets.json 服务。
  5. 将 'User Secrets' 添加到您的配置文件;这将取决于发生这种情况的确切位置。
  6. IConfiguration 注入您的控制器并将其保存到一个字段中。
  7. 调用您想要使用的数据:
    {yourConfigurationFieldName}.GetValue<string>({yourJsonKey})
    

在Visual Studio2022中,您可以通过修改launchSettings.json文件的以下部分来访问开发中的环境变量。

“环境变量”:{ "ASPNETCORE_ENVIRONMENT": "开发", "VaultUri": "https://xxx.vault.azure.net/", "AZURE_USERNAME": "xxx@user.com" }

其中 VaultUri 是您的环境变量的名称。