Customizing web.config for different environments
This is a very common scenario.
You develop your application in environment A. The production will run in environment B. There will be also a demo site in environment C and a test site in environment D. The environments may have different connection strings, account identities, custom application settings, whatever else you may or may not think of. You clearly need to give to every environment its own web.config file. Or modify the setting in run time depending on what environment the application is running in.
On other hand, your web.config includes sections common for all environments and you wouldn't like to maintain the same setting in four places. Another issue is that, when you publish the site, the development web.config is going to overwrite the target one that already has been customized for the target environment.
There is a simple solution with no coding involved. Make use of the configSource property for the sections you need to customize.
The configSource is basically the name of the include file in which the associated section is defined. Leave in the web.config only the sections common for all environments and take all variable sections out to separate files. For examle, the connectionString section in the web.config file will look like this:
<
connectionStrings configSource="SiteSettings\connectionStrings.config"/>
Note that the configSource is set to the physical location of the file relatively to the location of the web.config.The content of the connectionStrings.config will be:
<?
xml version="1.0" encoding="utf-8" ?>
<!-- This file is an extension of the application web.config file. The root element must be <connectionStrings>.-->
<connectionStrings>
<
add name="SiteSqlServer" connectionString="Integrated Security=SSPI;database=DbDemo;" />
</
connectionStrings>
You can make separate config files for as many sections as you wish. Put them all in a single directory. In our case it is SiteSettings.
Now, in our example with four environments you would make four sets of section config files in four directories and deploy each one to the corresponding environment. It is important not to include any of the config section directories into your solution. This will ensure that you won't overwrite the correct settings on the target site with your development ones on every publishing.
Now you can modify the common sections of your web.config and publish it to all targets. The targets will keep their customized config sections intact.