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

Yur*_* N. 4 c# asp.net web-config 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>
Run Code Online (Sandbox Code Playgroud)

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

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

San*_*ket 5

从 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"
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

由于 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>
Run Code Online (Sandbox Code Playgroud)

这个环境值将使用 - 跨应用程序读取

Environment.GetEnvironmentVariable("TEST_WEBCONFIG_VARIABLE");
Run Code Online (Sandbox Code Playgroud)

笔记!它仅在发布的情况下有效。