c# .net core 2.1 系统环境变量控制台应用程序未加载

c# .net core 2.1 system environment variable console application not loading

我正在使用 c# .net core 2.1 CONSOLE 应用程序。我可以使用以下命令查看预定义的系统环境变量:

configuration.GetValue<string>("TMP") 

但是,当我创建一个新的系统变量时,它对应用程序是不可见的。

如果我将鼠标悬停在配置上,我会看到 JsonConfigurationProvider 和 EnvironmentVariablesConfigurationProvider,但我创建的未列出。

例如,我在名为 Database 的机器上创建了一个新的系统环境变量。我想我可以调用使用 configuration.GetValue("Database")

这就是我加载配置的方式。

configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables().Build();

有什么建议吗?请记住,我使用的是控制台应用程序而不是 ASP.NET.

您不应该更改 System Environment Variable,您必须更改 Project Environment Variable 通过右键单击项目并选择“属性”或直接打开 launchSettings.json,您将看到配置文件列表:

{
  ...
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
         "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebApplication14": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

编辑或添加变量时不要忘记重新启动应用程序。