ASP.NET Custom Configuration Settings in web.config

Your Web site may have a need for configuration settings like the email address your contact form should send to, your Google Maps API key, or whatever. You could store those in a database, and even cache them as a DataTable using System.Web.Caching, but ASP.NET actually provides an easier, more efficient method – store your configuration settings in a config section in your web.config. This method not only saves you from a trip to the database, and from adding another object to the cache (web.config is already cached), it has the added benefit of providing an easy way to silo your development, testing and production environments with different settings.

Add a configuration setionGroup to Web.config

<?xml version="1.0"?>
        <!-- ... -->
        <sectionGroup name="MyCustomConfigSection">
            <section name="MySettings" type="System.Configuration.NameValueSectionHandler"/>
            <add key="SomeSetting" value="SettingValue" />
            <add key="ContactFormEmail" value="" />

Create a Settings class to read your settings

using System;
using System.Web;
using System.Web.Security;
using System.Configuration;
using System.Collections.Specialized;

public class Settings
    static Settings()
        config = new NameValueCollection();
        config = (NameValueCollection)ConfigurationSettings.GetConfig("MyCustomConfigSection/MySettings");

    private static NameValueCollection config;

    public static string Get(string key)
        string rtn = "";
            rtn = config[key];
        catch (Exception ex)
            //handle the exception
        return rtn;

Implement It

string emailAddress = Settings.Get("ContactFormEmail");

One Comment

  1. Posted April 9, 2013 at 11:47 am | Permalink

    Hello there! This article could not be written any better!
    Looking at this post reminds me of my previous roommate!
    He constantly kept preaching about this. I will send this post to
    him. Pretty sure he will have a good read. Thanks for sharing!

Post a Comment

Required fields are marked *


%d bloggers like this: