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

时间:2017-05-11 10:51:21

标签: c# asp.net asp.net-core web-config

这是我的 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>

如何在TEST_WEBCONFIG_VARIABLE web.config 中阅读Startup.cs

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

2 个答案:

答案 0 :(得分:2)

很确定你只需要打电话:

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

有关设置列表: Environment.GetEnvironmentVariables().GetEnumerator();

因为您从配置而不是AppSettings

访问EnvironmentVariables

答案 1 :(得分:1)

从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");

注意!它只适用于发布。