Creating Custom Configuration Settings in ASP.NET

Creating Custom Configuration Settings in ASP.NET

SP.NET Web applications have a built-in way to access simple name/value configuration data. In the Web.config file, you can create an section that lets you store simple name/value pairs. For example, create a new ASP.NET project and add the following tag as a child of the element in your Web.config file:


The section contains two tags that define the key/value pairs. You can retrieve the values via the built-in ConfigurationSettings property of the Page object. To begin, create a new Web Form in your project, name it customItems.aspx, and add this code to the Page_Load event:

   Dim aKey As String   Response.Write(“


“) For Each aKey In ConfigurationSettings.AppSettings.Keys Response.Output.WriteLine(aKey & “=” & _ ConfigurationSettings.AppSettings.Item(aKey)) Next

Figure 1. ConfigSections: The relationship between configuration file sections, tags, and handlers.

Compile and run the customItems.aspx Web Form. You’ll see the tag values. The loop retrieves all the tags from the section, and displays the key and value attribute values (see the sidebar “TIP: Using the Response.Output.WriteLine Method” for a discussion of how the code writes individual HTML lines). This simple key/value mechanism is perfect for many common needs, such as storing database connection strings at application scope; but it’s not robust enough for more complex data. Fortunately, Microsoft also built in a mechanism for creating custom configuration data. Rather than reading a hard-coded list of tags recognized only via code within a specific application, the ASP.NET framework reads one or more sections, which define the tag names the framework should expect to find in the remainder of the file and also define a class type and location for handling that particular type of content (see Figure 1).

As the ASP.NET engine parses the configuration file, it builds a list of the possible tags by reading the element’s

tags, each of which contains a name and a type, that define the names of the tags expected in the remainder of the document and a handler for that particular tag. A little experimentation shows you how this works. In the Web.config file for your project, add a new tag just before the ending tag in the file.


Save the Web.config file and run the project. You’ll get an “Unrecognized configuration in section ‘customItems’” error. The error occurs because there’s no section handler defined for the tag. But if you look at the entire Web.config file, there are no handlers defined for any of the tags, which leads to the question: Where are the handlers defined? (If you’re performing the steps as you read this article, remove the tag from your Web.config file before you continue.)

It turns out that there are two configuration files for every Web application: a root machine.config file, stored in a system folder, and the Web.config file in your application’s root folder. You can find the machine.config file in the $System$Microsoft.NETFrameworkCONFIG folder, where corresponds to the version of the framework installed and active on your server. The configuration settings in the machine.config file apply to all applications on your server unless overridden by more localized settings. If you look at the machine.config file, you’ll see a tag containing a set of

tags?and those tags define the handlers for the default tags you see in the web.config file. To make the process even simpler to understand, you can further group the

tags inside tags, each of which defines a set of handlers for related section tags.

The reason I brought up the machine.config file is because there are two ways to add custom tags. You can use one of the default System handler types to parse the content of your custom tags, or you can create your own handler.

Author Note: The Version and PublicKeyToken values may differ on your version of the .NET framework. To find the appropriate values for your system, copy them from an existing


2. Test the new tag by placing the new tag in your Web.config file, just before the closing tag, for example:

3. Save your changes to the web.config file. In your customItems.aspx Web Form, add the highlighted code to the Page_Load event:

   Dim aKey As String   Response.Write(“


“) For Each aKey In ConfigurationSettings.AppSettings.Keys Response.Output.WriteLine(aKey & “=” & _ ConfigurationSettings.AppSettings.Item(aKey)) Next Response.Write(“


“) For Each aKey In CType(ConfigurationSettings.GetConfig _ (“customSystemItems”), _ System.Collections.Specialized.NameValueCollection).Keys Response.Output.WriteLine(aKey & “=” & _ ConfigurationSettings.AppSettings.Item(aKey)) Next

4. Now compile and run the Web Form again. This time, you’ll see the CustomSystemItem header followed by the line “SomeKey=SomeValue“, which corresponds to the single child element you added to the element.

By modifying the machine.config file, you can use the defined custom tag in any Web application running on your server?but you may not always want the handler to apply to all applications. If you don’t, you can add a tag and the

tag to your web.config file instead. To test this, first remove the

tag you defined earlier from your machine.config file, and save the changes. Next, add a tag immediately following the opening tag in your web.config file, and place the

tag inside that, for example:


5. So that you can see a change, append one more tag to the section of your web.config file:

Save the changes to your web.config file and run the customItems.aspx Web Form again. You will see two values now rather than one. You don’t need to recompile your application to perform the test. ASP.NET applies configuration changes immediately.

You can define any number of custom tags in this manner; however, using the generic tags and the key and value attribute names isn’t particularly intuitive. For maintainability, it’s more effective to create custom tags that control both the tag and attribute names.

Defining Custom Handlers for Custom Tags
Suppose you wanted to define a list of articles, each of which has a title, a URL, and zero or more authors. A tag structure such as the following would be much easier to maintain than the generic :

Russell Jones
Russell Jones Barry Jones
Add the tag and its contents (the preceding XML fragment) to your Web.config file, just before the ending tag and save your changes.

Author Note: Don’t run the project yet. If you run the project now, you’ll get an error because there’s no handler defined for the section.

To read the tag from a configuration file, you need to create a custom handler. Creating a custom handler is not difficult, but requires a separate project, because the handler implementation searches for an exe or dll file with the handler name. I’ll walk you through the process in VB.NET, but I’ve included functionally identical code in C# as well in the downloadable code for this article (see the References section).

Create a new Class Library project and name it CustomItemHandler. Delete the default class that VS creates and add a new class named CustomTagHandler to the project. Custom handlers must implement the IConfigurationSectionHandler interface, which has only one method, called Create. The method takes three parameters: a parent object, an HttpConfigurationContext object, and a section XmlNode.

   Imports System   Imports System.Collections   Imports System.Xml   Imports System.Configuration      Public Class CustomTagHandler      Implements IConfigurationSectionHandler      Public Function Create(ByVal parent As Object, _      ByVal configContext As Object, _      ByVal section As System.Xml.XmlNode) As Object _      Implements System.Configuration. _      IConfigurationSectionHandler.Create      ‘ Implementation here   End Class
When the ASP.NET framework reads the node, it creates an instance of the CustomTagHandler class and calls its Create method. The XmlNode parameter contains the settings you want to read?in this example, the custom tag and its contents. Of the three parameters, you would typically only use the XmlNode, but to be complete, the parent object contains the configuration settings from any corresponding parent configuration section. The configContext parameter is an instance of the HttpConfigurationContext class and is useful primarily for obtaining the virtual path to the Web.config file.

You’re free to make the contents of custom configuration sections as simple or as complex as you like. I’ve elected to make this example more complex than a simple name/value pair so that you can see some of the possibilities inherent in using XML-formatted configuration files.

The Create method returns an Object. You can decide which type of object you want to return, but because you’re implementing an interface method, you can’t change the return type; therefore, code that calls your custom handler must cast the object to the correct type.

The CustomTagHandler class reads the list of child articles from the tag and populates an ArrayList with a list of Article objects. Each Article object has three public read-only properties that hold the title, the URL, and the list of authors for each article. Note that because there may be an arbitrary number of authors, the Article object implements the list of authors as an ArrayList as well. It’s important to realize that you do not have to treat the data in this manner. You could just as easily return the XML node itself and let the calling program deal with extracting the data, or you could return the author list as a collection of XML nodes, or?whatever you need. The point is that creating a custom handler lets you treat the data however you like. Here’s the full code for the CustomTagHandler class and the Article class.

   Imports System   Imports System.Collections   Imports System.Xml   Imports System.Configuration      Public Class CustomTagHandler      Implements IConfigurationSectionHandler      Public Function Create(ByVal parent As Object, _      ByVal configContext As Object, _      ByVal section As System.Xml.XmlNode) As Object _      Implements System.Configuration. _      IConfigurationSectionHandler.Create         Dim NArticle, NAuthor As XmlNode         Dim articleNodes, authorNodes As XmlNodeList         Dim authors As ArrayList         Dim aTitle As String         Dim aURL As String         Dim articles As New ArrayList()            articleNodes = section.SelectNodes(“article”)         For Each NArticle In articleNodes            aTitle = NArticle.Attributes.GetNamedItem(“title”).Value            aURL = NArticle.Attributes.GetNamedItem(“url”).Value            authors = New ArrayList()            authorNodes = NArticle.SelectNodes(“authors//author”)            If Not authorNodes Is Nothing Then               For Each NAuthor In authorNodes                  authors.Add(NAuthor.InnerText)               Next            End If            articles.Add(New Article(aTitle, aURL, authors))         Next         Return articles      End Function   End Class      Public Class Article      Private m_title, m_url As String      Private m_authors As ArrayList      Public Sub New       (ByVal aTitle As String, ByVal aURL As String, ByVal authors As ArrayList)         m_title = aTitle         m_url = aURL         m_authors = authors      End Sub         Public ReadOnly Property Title() As String         Get            Return m_title         End Get      End Property         Public ReadOnly Property URL() As String         Get            Return m_url         End Get      End Property         Public ReadOnly Property Authors() As ArrayList         Get            Return m_authors         End Get      End Property      End Class

Using the CustomItemHandler
Now you’re ready to test the CustomItemHandler class. First, make sure your code compiles without errors. To test the class, you need to add the

tag that defines your custom handler for the tag. Switch back to the ASP.NET project you started at the beginning of this article and add a reference to the CustomItemHandler.dll file created when you compiled the CustomItemHandler project. To create the reference, right-click on the References item in the Solution Explorer window and select Add Reference. Click the .NET tab and then click the Browse button. You’ll find the DLL in the bin subdirectory of your CustomItemHandler project.

Next, make one more modification to your Web.config file. Within the tag you created earlier, add a new

tag. Set the name attribute to “articlesVB” and set the type attribute to the class and assembly name of the handler you just created. At this point, the section should look like this (your version numbers may differ):


WARNING: The Web.config file is XML and is therefore case sensitive! Make sure the attribute values match the case for both the tag and the assembly and class names.

Add the following code to your customItems.aspx Web Form to retrieve and display the articles as links:

   Dim articles As ArrayList   Dim anArticleVB As CustomItemHandler.Article   Dim o as Object   Dim s As String   Response.Write(“


“) articles = CType(System.Configuration. _ ConfigurationSettings.GetConfig _ (“articlesVB”), ArrayList) If Not articles Is Nothing Then For Each o In articles anArticleVB = CType(o, CustomItemHandler.Article) Response.Output.WriteLine _ (“” & anArticleVB.Title & _ ““) If Not anArticleVB.Authors Is Nothing Then s = “by ” For Each obj In anArticleVB.Authors s += CType(obj, String) & “, ” Next Response.Output.WriteLine _ (s.Substring(0, s.Length – 2)) End If Next End If

Finally, compile and run the customItems.aspx Web Form. You’ll see the header “ArticlesVB” followed by the list of article links defined by the section in the Web.config file (see Figure 2).

Figure 2. Web.config File: The list of links from the custom configuration section in the Web.config file.

You can follow the steps in this article to create custom handlers for any type of information that you can store in a configuration file. You’ve seen how to use the built-in section to read generic key/value settings, how to use System-defined handlers to read custom sections with system-defined attributes, and how to create and define custom handlers. Define your handlers in the machine.config file when you want to use custom sections across all ASP.NET applications on a particular server or define them in the web.config file when you want to create custom sections that apply to only a single application.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist