How to: Create Custom Configuration Sections Using ConfigurationSection

You can extend ASP.NET configuration settings with XML configuration elements of your own. To do this, you create a custom configuration section handler. The handler must be a .NET Framework class that inherits from the System.Configuration.ConfigurationSection class. The section handler interprets and processes the settings that are defined in XML configuration elements in a specific section of a Web.config file. You can read and write these settings through the handler's properties.

To create a custom configuration section handler

  1. Create a public class that inherits from the System.Configuration.ConfigurationSection class.

  2. Add code to define the section's attributes and elements.

    The following example shows how to create a handler for a custom configuration section named "PageAppearance." The section has a RemoteOnly attribute and Font and Color elements. The code shows how to use string, integer, and Boolean attributes. It also shows how to use string and integer validators for those attributes. (The Boolean attribute is automatically validated.) The validators check the format of the configuration markup at run time and throw exceptions if the values provided for the custom attributes do not meet the specified criteria.

    Imports System
    Imports System.Collections
    Imports System.Text
    Imports System.Configuration
    Imports System.Xml
    Namespace Samples.AspNet
        Public Class PageAppearanceSection
            Inherits ConfigurationSection
            ' Create a "remoteOnly" attribute.
            <ConfigurationProperty("remoteOnly", DefaultValue:="false", IsRequired:=False)> _
            Public Property RemoteOnly() As Boolean 
                    Return CType(Me("remoteOnly"), Boolean)
                End Get 
                Set(ByVal value As Boolean)
                    Me("remoteOnly") = value
                End Set 
            End Property 
            ' Create a "font" element.
            <ConfigurationProperty("font")> _
            Public Property Font() As FontElement
                    Return CType(Me("font"), FontElement)
                End Get 
                Set(ByVal value As FontElement)
                    Me("font") = value
                End Set 
            End Property 
            ' Create a "color element."
            <ConfigurationProperty("color")> _
            Public Property Color() As ColorElement
                    Return CType(Me("color"), ColorElement)
                End Get 
                Set(ByVal value As ColorElement)
                    Me("color") = value
                End Set 
            End Property 
        End Class 
        ' Define the "font" element 
        ' with "name" and "size" attributes. 
        Public Class FontElement
            Inherits ConfigurationElement
            <ConfigurationProperty("name", DefaultValue:="Arial", IsRequired:=True), _
             StringValidator(InvalidCharacters:="~!@#$%^&*()[]{}/;'\""|\\", MinLength:=1, MaxLength:=60)> _
            Public Property Name() As String 
                    Return CType(Me("name"), String)
                End Get 
                Set(ByVal value As String)
                    Me("name") = value
                End Set 
            End Property
            <ConfigurationProperty("size", DefaultValue:="12", IsRequired:=False), _
             IntegerValidator(ExcludeRange:=False, MaxValue:=24, MinValue:=6)> _
            Public Property Size() As Integer 
                    Return CType(Me("size"), Integer)
                End Get 
                Set(ByVal value As Integer)
                    Me("size") = value
                End Set 
            End Property 
        End Class 
        ' Define the "color" element  
        ' with "background" and "foreground" attributes. 
        Public Class ColorElement
            Inherits ConfigurationElement
            <ConfigurationProperty("background", DefaultValue:="FFFFFF", IsRequired:=True), _
             StringValidator(InvalidCharacters:="~!@#$%^&*()[]{}/;'\""|\\GHIJKLMNOPQRSTUVWXYZ", MinLength:=6, MaxLength:=6)> _
            Public Property Background() As String 
                    Return CType(Me("background"), String)
                End Get 
                Set(ByVal value As String)
                    Me("background") = value
                End Set 
            End Property
            <ConfigurationProperty("foreground", DefaultValue:="000000", IsRequired:=True), _
             StringValidator(InvalidCharacters:="~!@#$%^&*()[]{}/;'\""|\\GHIJKLMNOPQRSTUVWXYZ", MinLength:=6, MaxLength:=6)> _
            Public Property Foreground() As String 
                    Return CType(Me("foreground"), String)
                End Get 
                Set(ByVal value As String)
                    Me("foreground") = value
                End Set 
            End Property 
        End Class 
    End Namespace

    This example uses the declarative model. A configuration section handler can also be implemented programmatically. For an example, see Classes Used to Create Custom Section Handlers and the System.Configuration.ConfigurationSection class overview.

To add a custom section handler to an ASP.NET configuration file

  1. In the Web.config file, add a sectionGroup element and a section element inside the configSections element, as shown in the following example. The declaration associates the custom section handler with the section name.

    Note Note

    Nesting a section element in a sectionGroup is optional, but we recommend doing this to help organize configuration data.

    <!-- Configuration section-handler declaration area. -->
        <sectionGroup name="pageAppearanceGroup">
          <!-- Other <section> and <sectionGroup> elements. -->
      <!-- Configuration section settings area. -->

    You can add the section-handler declaration in a different configuration file than the one where you add the custom configuration elements, providing that the configuration file where the section handler is declared is higher in the configuration file hierarchy. If you add the section handler declaration to a configuration file that is outside of your application, you must do the following:

    • Include the assembly that defines the section in the same directory as the Web.config file.

    • Ensure that the type attribute of the section element matches the manifest of the assembly (ensure that you specify both the correct namespace and type name).

    If either of these conditions is not fulfilled, a configuration error will be thrown. For more information, see ASP.NET Configuration File Hierarchy and Inheritance.

  2. Add custom configuration elements in the configuration section settings area of the Web.config file, as shown in the following example:

    <!-- Configuration section-handler declaration area. -->
      <!-- Configuration section settings area. -->
        <pageAppearance remoteOnly="true">
          <font name="TimesNewRoman" size="18"/>
          <color background="000000" foreground="FFFFFF"/>
      <!-- Other configuration settings, such as system.web -->

To programmatically access custom configuration data

  • Get an instance of the custom configuration object and use the GetSection method or the GetSection method to populate it.

    The following example shows an ASP.NET Web page that works with the previous examples to enumerate the attributes and child elements of the custom configuration section.

    <%@ Page Language="VB"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
    <script runat="server">
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        Dim config As Samples.AspNet.PageAppearanceSection = _
          CType(System.Configuration.ConfigurationManager.GetSection( _
            "pageAppearanceGroup/pageAppearance"),  _
        Response.Write("<h2>Settings in the PageAppearance Section:</h2>")
        Response.Write("RemoteOnly: " _
                        + config.RemoteOnly.ToString() + "<br>")
        Response.Write("Font name and size: " _
                        + config.Font.Name + " " _
                        + config.Font.Size.ToString() + "<br>")
        Response.Write("Background and foreground color: " _
                        + config.Color.Background + " " _
                        + config.Color.Foreground + "<br>")
      End Sub
    <html xmlns="">
    <head runat="server">
      <title>Custom Configuration Section Example</title>
      <form id="form1" runat="server">