SteGriff

Blog

Next & Previous

Confusing things about web.config

When I started professional .Net development, nobody explained these app.config and web.config gotchas to me, so here we go:

1. Whichever project you’re running is the one that needs the config

Say you have two projects (although it’s never this simple):

…where the DAL connects to the database and the Web project includes the DAL as a reference.

The one where you need to configure the connectionString is… MyCorp.Web!

This is so that every calling project can set the config for MyCorp.Data.DAL differently; they can each re-use it in their own way without being tied to a single hard database connection.

It’s more convoluted when one runnable project includes another as a reference, so just rememeber to configure the one you’re currently running.

2. You have to Publish to get transformed Configs

(If you’ve forgotten how to set up config transforms it turns out I wrote a thing this time last year)

You would think that if you set the little dropdown at the top of the screen to ‘Release’, that running the project would use ‘web.Release.config’. Nope!

Config transforms are only processed when you Publish the project, or if you use extra tooling. At my currently employer, we have a CLI tool to transform all your configs to a given configuration, precisely for this reason.

This generally means that your web.Debug.config is never used for anything and you can probably ignore it.

3. You can tailor how much effect a Config Transform has over each area

Config transforms use Microsoft’s special XML Document Transform (XDT) syntax.

In a file like ‘web.Release.config’ You may notice some whole blocks which are marked ‘replace’:

<connectionStrings xdt:Transform="Replace">
	<!-- Release mode connection strings -->
	<add name="PoliciesDb" connectionString="..." providerName="System.Data.SqlClient" />
</connectionStrings>

…this says, replace the entire content of the original connectionStrings block from web.config with what I’ve got in here.

Others are more targetted, fine-grained changes:

<appSettings>
	<add key="RootUrl" value="https://test.example.com" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>

Instead of replacing all appSettings, we’re just targetting the one we want to change. The Locator says to Match on the key of the appSetting (in this case ‘RootUrl’), and if found in web.config, replace it with the value from this entry.

All the other appSettings in the original web.config are left alone.

Summary

Remember:

  1. Put the config in the project you’re running
  2. Config transforms don’t do anything when you run the project, only when you Publish
  3. Check whether your transforms target whole blocks or just individual key-values!

Hope this helps you, especially if you’re starting out!