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

标签 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>

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

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

最佳答案

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

注意!它仅在发布时有效。

关于c# - 从 Asp.Net Core 中的 web.config 读取环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43913320/

相关文章:

c# - 指定的架构无效。错误 : error 0002: Request failed

c# - 如何获得不同的列表?

c# - 比较手写 ADO/Sprocs 与 nHibernate

c# - 注入(inject)的 HttpContext 始终为 null

c# - 按字符串属性对对象进行排序,最后为空字符串

c# - 如何在C#中更改元素类的属性

C# MongoDB LINQ : Cannot query nested list

c# - 允许对 App_Data 的请求

css - 将 CssClass 添加到 asp :ListItem within CheckBoxList

linux - postgres用户的很多tracepath命令