Platinum Partner

Get AppSettings from web.config in a generic way

I use this snippet in all web projects where I need to get settings from the AppSettings section in web.config. This method (static or not) makes it easy and clean to get settings converted to the type I need. Also it enables default values to be fetched if the setting doesn't exist or can be converted to the specified type.

It can be used in different ways, like so;

<!-- Imagine we have these settings: -->
<appSettings>
    <add key="Title" value="Web title" />
    <add key="VersionNumber" value="5" />
    <add key="UseThemes" value="True" />
    <add key="WebTheme" value="Light" />
</appSettings>

And we could call it like this:

string title = GetAppSetting<string>("Title", "My title");

Even better, we could let the type be inferred from the second parameter and call it like this:

string title = GetAppSetting("Title", "My title");
int version = GetAppSetting("VersionNumber", 123);
bool useThemes = GetAppSetting("UseThemes", false);

We could also use enums, like so:

// Imagine this enum:
enum MyThemes
{
    Light,
    Dark,
    Office
}

And this would easily be called like this:

MyThemes theme = GetAppSetting("WebTheme", MyThemes.Office);

This snippet could, of course, be extended with an overload for throwing exceptions, like so:

public static T GetAppSetting(string key, T defaultValue)
{
    return GetAppSetting(key, defaultValue, false);
}

// New parameter: bool throwExceptions
public static T GetAppSetting(string key, T defaultValue, bool throwExceptions)
{
    ...
            try
            {
                ...
            }
            catch
            {
                if (throwExceptions)
                    throw;
            }
    ...
}
public static T GetAppSetting(string key, T defaultValue)
{
    if (!string.IsNullOrEmpty(key))
    {
        string value = ConfigurationManager.AppSettings[key];
        try
        {
            if (value != null)
            {
                var theType = typeof(T);
                if (theType.IsEnum)
                    return (T)Enum.Parse(theType, value.ToString(), true);

                return (T)Convert.ChangeType(value, theType);
            }

            return default(T);
        }
        catch { }
    }

    return defaultValue;
}
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}