Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing web.config file based on an Environment Variable in ASP.NET

I need to change my connection string in the web.config file based on an environment variable (for different enviornments, like dev/staging/production, etc). I have seen other solutions that use build tasks to accomplish changing different configurations, but haven't been able to find something that will let me change my connection string based on an environment variable. Does anyone know of any way to do this?

like image 869
Ryan Avatar asked Jul 16 '09 21:07

Ryan


2 Answers

We make use of the configSource attribute for the appSettings and connectionStrings elements in the web.config.

Basically, we have the same web.config file for all of our environments: dev, qa and production.

Then we utilize seperate "environment specific" files.. For example...

In web.config:

<?xml version="1.0"?>
<configuration>
  <appSettings configSource="local.appsettings.config" />
  <connectionStrings configSource="local.connectionstrings.config" />
</configuration>

Then we maintain the following files:

local.appsettings.config.development
local.appsettings.config.qa
local.appsettings.config.production
local.connectionstrings.config.development
local.connectionstrings.config.qa
local.connectionstrings.config.production

Since we pre-compile all of our asp.net applications before deployment, we've got a custom msBuild task utilized by our CI solution that copies the right configuration files (based on the target environment) to the proper .config file...

So, if we are deploying to dev, local.appsettings.config.development -> local.appsettings.config

If we are deploying to qa, local.appsettings.config.qa -> local.appsettings.config

This allows us to keep the core web.config the same across all of our environments.

like image 103
datacop Avatar answered Sep 20 '22 06:09

datacop


How about having two connection strings and another variable, like "isTesting" in your web.config, then based on the value of isTesting pick which connection string to use?

like image 29
Cᴏʀʏ Avatar answered Sep 21 '22 06:09

Cᴏʀʏ