Thursday, September 10, 2009

Store Server-specific Settings in External Config File

I just learned that the appSettings node in an ASP.NET web.config file can reference an external configuration file. This is extremely handy for managing values that change depending on whether the site’s on development, staging, or production servers.

Take this example: you have a simple contact form that sends an email. On the live, production site, you want that email to go to someone in customer service. However, in a development or testing environment, you probably want that email to go to a developer or QA tester.

Here’s how to set it up:

In the web.config:

   1: <appSettings>



   2:     <add key="CSEmail" value="customer.service@somecompany.com"/>



   3: </appSettings>




Then in the appSettings.config file:





   1: <appSettings>



   2:     <add key="CSEmail" value="developer@testdomain.com"/>



   3: </appSettings>




ASP.NET will attempt to load the appSettings.config, with any keys overriding those in the web.config. If appSettings.config exists on the development server, it will read developer@testdomain.com as the value. If the file doesn’t exist, it will use customer.service@somecompany.com as the value.



So, in our example, we would simply not upload our appSettings.config to the production server.



Easy. Peasy. Lemon squeezy.