TonyP
TonyP

Reputation: 5873

How to conditionally return web.config entry

How do I return web.config entry conditionally. I.E: If the web.config folder is 'C:\inetpub\www\myTestSite' then return 'connectionString' TestDB else return 'ProdDB'

Upvotes: 2

Views: 1068

Answers (2)

Pavel Nikolov
Pavel Nikolov

Reputation: 9541

It is much better to use different config files for the different wnvironments.

You can have the following in your web.config file:

<connectionStrings configSource="SiteSettings\connectionStrings.config"/>

where the configSource is path relative to the path of the web.config file. Then you can easily create 4 different connectionStrings.config files in your project: connectionStrings.config.dev, connectionStrings.config.test, connectionStrings.config.staging, connectionStrings.config.prod. With that set up you can configure your build process to automatically choose the right connectionStrings.config file for the right environment. This way maintenance will be a lot easier.

ScottGu has an article describing this method. And one more article about Customizing web.config for different environments which you may find helpful.

Upvotes: 2

wsanville
wsanville

Reputation: 37516

You can try something like this:

string conn;
if (Server.MapPath("~/web.config").StartsWith(@"C:\inetpub\www\myTestSite"))
    conn = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;
else
    conn = ConfigurationManager.ConnectionStrings["ProdDB"].ConnectionString;

Although I would recommend a different approach, either by using separate config files for your sites or by using a more sophisticated method of testing where your code is located. What I do is put a key in appSettings in the machine.config file for my development machine, as well as my test, and production web servers so that my application knows what environment it is running on. I use the value of that appSetting to determine which connection string to use.

Upvotes: 3

Related Questions