ASP.NET appSettings Example

ASP.NET web programming framework

You want to store strings or other values in the appSettings section of Web.config in your ASP.NET website project. Keeping constants in non-code files allows changes to be made easier. Here we see how to use this feature in the Web.config file in ASP.NET.

This C# article shows how to access AppSettings in ASP.NET. It uses properties.

Introduction

We will use an AppSettings block in Web.config, which is a text file that ASP.NET treats specially for your project. It is good for keeping strings such as site titles, certain other site-wide variables such as style sheet titles, or certain page names.

Example keys: SiteName
SiteTitle

Example values: New York Times
Breaking News, World News, and Multimedia

Add values to AppSettings

Here we add the appropriate markup to the Web.config file. First, open your Web.config file in the Solution Explorer. Find the <configuration> container tag, and add an <appSettings> section.

Web.config that uses appSettings [XML]

<?xml version="1.0"?>
<configuration>
    <configSections>
    <!-- some stuff omitted here -->
    <appSettings>
	<add key="SiteTitle" value="Breaking News, World News, and Multimedia"/>
	<add key="SiteName" value="New York Times"/>
    </appSettings>
    <!-- more stuff.... -->

Example

Here we use the AppSettings collection. One good way to use AppSettings in the C# code is to encapsulate the values in properties. We will use the C# getter syntax to access the above properties.

Encapsulate Field
Page that uses AppSettings [C#]

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;

public partial class _Default : Page
{
    public string RootTitle
    {
	get
	{
	    // Returns the title string.
	    return WebConfigurationManager.AppSettings["SiteTitle"];
	}
    }

    public string RootName
    {
	get
	{
	    return WebConfigurationManager.AppSettings["SiteName"];
	}
    }

    protected void Page_Load(object sender, EventArgs e)
    {
	// Access the properties (and thus Web.config) like this.
	this.Title1.Text = this.RootName + " - " + this.RootTitle;
    }
}
Note (please read)

Description. It includes System.Web.Configuration. Note the using line at the top where this namespace is included. WebConfigurationManager is only present in this namespace.

Property usage. Above, RootTitle and RootName are defined and used. Look at how they are called with "this" in the Page_Load method. That is a good way to use properties like these without causing confusion. Finally, it uses string lookup key on AppSettings to get the correct value. It is a NameValueCollection, which is just a "specialized" hashtable.

NameValueCollection

Cache

It is possible to cache the results from appSettings. Here is an optimization that not only makes the code 30 times faster, but also allows better code separation and clarity. We will use ASP.NET global variables. Here are the settings in Web.config.

Web.config appSettings keys [XML]

<?xml version="1.0"?>
<configuration>
    <appSettings>
	<add key="SiteTitle" value="The New York Times - Breaking News..."/>
	<add key="SitePrefix" value="NYT"/>
	<add key="SiteHeader" value="Breaking News, World News & Mutimedia"/>
	<add key="BaseUrl" value="http://nytimes.com/"/>
    </appSettings>

Encapsulate settings. Using properties is ideal for these appSettings. My first appSettings article demonstrates this, but the properties are slow because they cause repeated NameValueCollection lookups. We can make a new class in App_Code, and fill it as follows.

SiteGlobal class that caches appSettings [C#]

using System;
using System.Web;
using System.Web.Configuration;

public static class SiteGlobal
{
    /// <summary>
    /// Full site title tag at root.
    /// </summary>
    static public string RootTitle { get; set; }

    /// <summary>
    /// Header prefix on root page.
    /// </summary>
    static public string RootPrefix { get; set; }

    /// <summary>
    /// Header main part on root page.
    /// </summary>
    static public string RootHeader { get; set; }

    /// <summary>
    /// Main site Url with http://.
    /// </summary>
    static public string BaseUrl { get; set; }

    static SiteGlobal()
    {
	// Cache all these values in static properties.
	RootTitle = WebConfigurationManager.AppSettings["SiteTitle"];
	RootPrefix = WebConfigurationManager.AppSettings["SitePrefix"];
	RootHeader = WebConfigurationManager.AppSettings["SiteHeader"];
	BaseUrl = WebConfigurationManager.AppSettings["BaseUrl"];
    }
}
Property (Icon copyright Microsoft)

Using static classes. Static classes are useful for holding static methods and enforce code correctness. There is a static constructor that sets the properties. When the ASP.NET AppDomain for this site is initialized the properties will be accessed and cached. It has static public properties. Properties can be static just like variables and methods. These properties can be accessed without a class instance.

Access cached values. Now we can simply call into the SiteGlobal class and use the properties there for access to the appSettings. Using the cached values is 30 times faster, and will reduce memory pressure.

Example Page_Load event handler [C#]

protected void Page_Load(object sender, EventArgs e)
{
    Title1.Text = SiteGlobal.RootTitle;
    Prefix1.InnerHtml = SiteGlobal.RootPrefix;
    Header1.InnerHtml = SiteGlobal.RootHeader;
}

Review: We saw how you can cache appSettings in ASP.NET with a static class and static properties. This provides clearer code and also improves performance. This could cut milliseconds off of your page load times.

Summary

We saw how you can use Web.config and appSettings to store values that are specific to the current deployment. These should not be changed frequently, but be stored separate from the code to reduce complexity. Finally, consider caching AppSettings for speed.

ASP.NET Tutorials
.NET