asp.net-mvc 你如何在 web.config 中放置环境变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29416302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:25:35  来源:igfitidea点击:

How do you put environmental variables in web.config?

asp.net-mvcazureweb-configconnection-stringappsettings

提问by Joseph Casey

I am currently Following these tutorials, and I am wanting to call the clear text string from Azure's Application Settings for Web Apps. I am under the impression that environmental variables are used for non-config files. However, I am wanting to use the same methodology for web.config files.

我目前正在关注这些教程,我想从 Azure 的 Web 应用程序应用程序设置中调用明文字符串。我的印象是环境变量用于非配置文件。但是,我想对 web.config 文件使用相同的方法。

  <connectionStrings configSource="/config/ConnectionStrings.config">
    <add name="DefaultConnection" connectionString="@Environment.GetEnvironmentalVariable('SQLAZURECONNSTR_DefaultConnection')" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings file="config\AppSettingsSecret.config">
    <!-- Code Removed for Conciseness-->
    <add key="mailAccount" value="@Environment.GetEnvironmentalVariable('APPSETTING_mailAccount')" />
    <add key="mailPassword" value="@Environment.GetEnvironmentalVariable('APPSETTING_mailPassword')" />
    <!-- Twilio-->
    <add key="TwilioSid" value="@Environment.GetEnvironmentalVariable('APPSETTING_TwilioSid')" />
    <add key="TwilioToken" value="@Environment.GetEnvironmentalVariable('APPSETTING_TwilioToken')" />
    <add key="TwilioFromPhone" value="@Environment.GetEnvironmentalVariable('APPSETTING_TwilioFromPhone')" />
  </appSettings>

Note: I included the configSource="/example/" for local testing.

注意:我包含了 configSource="/example/" 用于本地测试。

回答by Richard

For Applications, including Web Applications, On Windows:

对于应用程序,包括 Web 应用程序,在 Windows 上:

The values in <appSettings>are just strings. If you want environmental variables to be expanded your application will need to do that itself.

中的值<appSettings>只是字符串。如果您希望扩展环境变量,您的应用程序将需要自行完成。

A common way of doing this is to use the cmdsyntax %variable%and then using Environment.ExpandEnvironmentVariablesto expand them.

这样做的一种常见方法是使用cmd语法%variable%,然后使用Environment.ExpandEnvironmentVariables来扩展它们。

On Azure:

在 Azure 上:

The rules are different (see links in the question): but the values appear to be in environment variables so, in the config file:

规则不同(请参阅问题中的链接):但值似乎在环境变量中,因此,在配置文件中:

<add key='SomeSetting' value='%APPSETTING_some_key%'/>

and then to retrieve:

然后检索:

var someSetting = Environment.ExpandEnvironmentVariables(
                     ConfigurationManager.AppSetting("SomeSetting"))

may well work.

可能很好用。