Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you put environmental variables in web.config?

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.

  <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.

like image 510
Joseph Casey Avatar asked Apr 02 '15 15:04

Joseph Casey


People also ask

How do you set environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

How do you display environment variables?

To display the values of environment variables, use the printenv command. If you specify the Name parameter, the system only prints the value associated with the variable you requested.

Where do I put the .env file?

env file is placed at the base of the project directory. Project directory can be explicitly defined with the --file option or COMPOSE_FILE environment variable.


1 Answers

For Applications, including Web Applications, On Windows:

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

A common way of doing this is to use the cmd syntax %variable% and then using Environment.ExpandEnvironmentVariables to expand them.

On 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.

like image 136
Richard Avatar answered Oct 14 '22 09:10

Richard