Share via


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 perform the configuration task or tasks.

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

    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

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

    <configuration>
    <!-- Configuration section-handler declaration area. -->
      <configSections>
        <sectionGroup name="pageAppearanceGroup">
          <section 
            name="pageAppearance" 
            type="Samples.AspNet.PageAppearanceSection" 
            allowLocation="true" 
            allowDefinition="Everywhere"
          />
        </sectionGroup>
          <!-- Other <section> and <sectionGroup> elements. -->
      </configSections>
    
      <!-- Configuration section settings area. -->
    
    </configuration>
    

    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. For more information, see ASP.NET Configuration File Hierarchy and Inheritance.

    The assembly file that contains the type defined by the section element must be in the same ASP.NET Web site directory as the Web.config file that references it. The type attribute of the section element must match the manifest of the assembly or a configuration error will be thrown.

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

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

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <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"),  _
          Samples.AspNet.PageAppearanceSection)
    
        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
    
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
      <title>Custom Configuration Section Example</title>
    </head>
    <body>
      <form id="form1" runat="server">
      <div>
        <h1>
      </div>
      </form>
    </body>
    </html>
    
    
    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
      protected void Page_Load(object sender, EventArgs e)
      {
        Samples.AspNet.PageAppearanceSection config =
            (Samples.AspNet.PageAppearanceSection)System.Configuration.ConfigurationManager.GetSection(
            "pageAppearanceGroup/pageAppearance");
    
        Response.Write("<h2>Settings in the PageAppearance Section:</h2>");
        Response.Write(string.Format("RemoteOnly: {0}<br>", 
            config.RemoteOnly));
        Response.Write(string.Format("Font name and size: {0} {1}<br>",
            config.Font.Name, config.Font.Size));
        Response.Write(
            string.Format("Background and foreground color: {0} {1}<br>",
            config.Color.Background, config.Color.Foreground));
      }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
      <title>Custom Configuration Section Example</title>
    </head>
    <body>
      <form id="form1" runat="server">
      <div>
        <h1>
      </div>
      </form>
    </body>
    </html>
    

See Also

Concepts

ASP.NET Configuration File Structure (Sections and Section Handlers)

ASP.NET Configuration Overview

Reference

System.Configuration.ConfigurationSectionGroup

System.Configuration.ConfigurationSection

System.Configuration.ConfigurationElement

System.Configuration.ConfigurationElementCollection

Other Resources

Administering ASP.NET Web Sites

Configuring Applications

Change History

Date

History

Reason

April 2009

Added links to related topics.

Customer feedback.