user3587624 user3587624 - 1 year ago 142
ASP.NET (C#) Question

Web.Debug.config vs. Web.Release.config running web app in localhost

I have a Web.config file with some entries in there but depending on whether I am in Debug or Release mode when I execute my Web Application locally, I want to take different appSettings.

For instance, let's say that I have the following entry in my Web.Debug.config appSettings.

<add key="MyServiceUrl" value="http://my-test-site:8080/" />

And also I have this in my Web.Release.config:

<add key="MyServiceUrl" value="http://my-prod-site:80/" />

How should I configure my Web.Config, Web.Debug.Config and Web.Release.Config so depending on the mode I run my application locally (Debug - Any CPU vs. Release - Any CPU), it takes the right one?

Right now, the only pair of key and value that it takes is the one from the main Web.Config regardless I select Debug or Release in Visual Studio.

How can I configure that behavior?


This is how I have defined Web.config

<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

This is how I have defined Web.Debug.config

<add key="MyServiceUrl" value="http://my-test-site:8080/" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>

This is how I have defined Web.Release.config

<add key="MyServiceUrl" value="http://my-prod-site:8080/" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />

Finally, in my code, I have the following method:

public static string GetAppSetting(string settingKey)
if (string.IsNullOrEmpty(settingKey))
throw new System.ArgumentException("Cannot fetch a setting for a null/empty setting key.");
return ConfigurationManager.AppSettings[settingKey];

which I call it like this:
string setting = GetAppSetting("MyServiceUrl");

However, it is null if it is not defined in the main Web.config

Answer Source

In the web.Release.config try this, it should work:

 <add key="MyServiceUrl" value="http://my-prod-site:8080/" xdt:Transform="Insert" />

Read this: Web.config Transformation Syntax for Web Application Project Deployment

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download