从 Asp.Net Core 中的 web.config 读取环境变量

Read environment variables from web.config in Asp.Net Core

这是我的 web.config 文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
      <environmentVariables>
        <environmentVariable name="TEST_WEBCONFIG_VARIABLE" value="some test webconfig variable value" />
      </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>

如何从 Startup.cs 中的 web.config 读取 TEST_WEBCONFIG_VARIABLE

我尝试了 Configuration["TEST_WEBCONFIG_VARIABLE"],但配置值列表中不存在此变量。

很确定你只需要打电话:

个人设置: Environment.GetEnvironmentVariable("TEST_WEBCONFIG_VARIABLE"‌​);

对于设置列表: Environment.GetEnvironmentVariables().GetEnumerator();

因为您是从配置而不是 AppSettings 访问 EnvironmentVariables

虽然 运行 来自 Visual Studio,但像这样使用 launchSettings.json-

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

因为launchSettings.json只限于Visual Studio,如果发布版本使用web.config这样-

<aspNetCore processPath="dotnet" arguments=".\MyAspNetCoreApplication.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" >
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
    <environmentVariable name="TEST_WEBCONFIG_VARIABLE" value="123" />
  </environmentVariables>
</aspNetCore>

并且此环境值将使用 -

跨应用程序读取
Environment.GetEnvironmentVariable("TEST_WEBCONFIG_VARIABLE");

注意!它仅在发布的情况下有效。