Ryan
Ryan

Reputation: 18109

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?

Upvotes: 11

Views: 12419

Answers (4)

Pablo Castilla
Pablo Castilla

Reputation: 2741

You can set a web.config for each environment in the configuration manager using prebuild events. I have tried this with excellent results.

http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx

When you have debug and build you can have local/preproduction/production... etc

Upvotes: 0

datacop
datacop

Reputation: 602

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.

Upvotes: 8

Nathan Tregillus
Nathan Tregillus

Reputation: 6334

you can also use config sections, and based upon server name switch between sections. this way you can have keys named the same.

link text

Upvotes: 0

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107498

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?

Upvotes: 2

Related Questions