How to: Create Custom Configuration Sections Using ConfigurationSection
You can extend the standard set of ASP.NET configuration settings with XML configuration elements of your own. To do this, you must create your own configuration section handler.
The handler must be a .NET Framework class that implements the System.Configuration.ConfigurationSection class.
Note |
---|
In the .NET Framework versions 1.0 and 1.1, a configuration section handler had to implement the System.Configuration.IConfigurationSectionHandler interface, which is now deprecated. However, a code example exists in How to: Create Custom Configuration Sections Using IConfigurationSectionHandler. |
The section handler interprets and processes the settings defined in XML configuration elements within a specific portion of a Web.config file and returns an appropriate configuration object based on the configuration settings. The configuration object that the handler class returns can be any data structure; it is not limited to any base configuration class or configuration format. ASP.NET uses the configuration object to read and write to your custom configuration element.
To create a custom configuration section handler
Create a public class that inherits the System.Configuration.ConfigurationSection class, as illustrated in the following code example.
Imports System Imports System.Collections Imports System.Text Imports System.Configuration Imports System.Xml Namespace MyConfigSectionHandler Public Class MyHandler Inherits ConfigurationSection Public Sub MyHander() End Sub ' Add declarations for child elements and attributes like this: '<ConfigurationProperty("<propertyName>", <named parameters>)> _ 'Public Property MyAttrib1() As <type> ' Get ' Return CStr(Me("<propertyName>")) ' End Get ' Set(ByVal value As <type>) ' Me("<propertyName>") = value ' End Set 'End Property End Class End Namespace
using System; using System.Collections; using System.Text; using System.Configuration; using System.Xml; namespace MyConfigSectionHandler { public class MyHandler : ConfigurationSection { public MyHandler() { } // Add declarations for child elements and attributes like this: // [ConfigurationProperty("<propertyName>", <named parameters>)] // public <type> <PropertyName> // { // get { return (<type>)this["<propertyName>"]; } // set { this["<propertyName>"] = value; } // } } }
Add your own code to perform the configuration work that you desire.
For example, you can replace the commented code with the following code that obtains the values from your custom section.
Imports System Imports System.Collections Imports System.Text Imports System.Configuration Imports System.Xml Namespace MyConfigSectionHandler Public Class MyHandler Inherits ConfigurationSection Public Sub MyHander() End Sub Public Sub MyHander(ByVal attribVal As String) MyAttrib1 = attribVal End Sub <ConfigurationProperty("myAttrib1", DefaultValue:="Clowns", IsRequired:=True)> _ <StringValidator(InvalidCharacters:="~!@#$%^&*()[]{}/;'\|\\", MinLength:=1, MaxLength:=60)> _ Public Property MyAttrib1() As String Get Return CStr(Me("myAttrib1")) End Get Set(ByVal value As String) Me("myAttrib1") = value End Set End Property <ConfigurationProperty("myChildSection")> _ Public Property MyChildSection() As MyChildConfigElement Get Return CType(Me("myChildSection"), MyChildConfigElement) End Get Set(ByVal value As MyChildConfigElement) Me("myChildSection") = CType(value, MyChildConfigElement) End Set End Property End Class Public Class MyChildConfigElement Inherits ConfigurationElement Public Sub MyChildConfigElement() End Sub Public Sub MyChildConfigElement( _ ByVal a1 As String, ByVal a2 As String) MyChildAttribute1 = a1 MyChildAttribute2 = a2 End Sub <ConfigurationProperty("myChildAttrib1", DefaultValue:="Zippy", IsRequired:=True)> _ <StringValidator(InvalidCharacters:="~!@#$%^&*()[]{}/;'\|\\", MinLength:=1, MaxLength:=60)> _ Public Property MyChildAttribute1() As String Get Return CStr(Me("myChildAttrib1")) End Get Set(ByVal value As String) Me("myChildAttrib1") = value End Set End Property <ConfigurationProperty("myChildAttrib2", DefaultValue:="Michael Zawondy", IsRequired:=True)> _ <StringValidator(InvalidCharacters:="~!@#$%^&*()[]{}/;'\|\\", MinLength:=1, MaxLength:=60)> _ Public Property MyChildAttribute2() As String Get Return CStr(Me("myChildAttrib2")) End Get Set(ByVal value As String) Me("myChildAttrib2") = value End Set End Property End Class End Namespace
using System; using System.Collections; using System.Text; using System.Configuration; using System.Xml; namespace MyConfigSectionHandler { public class MyHandler : ConfigurationSection { public MyHandler() { } public MyHandler(String attribVal) { MyAttrib1 = attribVal; } [ConfigurationProperty("myAttrib1", DefaultValue = "Clowns", IsRequired = true)] [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] public String MyAttrib1 { get { return (String)this["myAttrib1"]; } set { this["myAttrib1"] = value; } } [ConfigurationProperty("myChildSection")] public MyChildConfigElement MyChildSection { get { return (MyChildConfigElement)this["myChildSection"]; } set { this["myChildSection"] = value; } } } public class MyChildConfigElement : ConfigurationElement { public MyChildConfigElement() { } public MyChildConfigElement(String a1, String a2) { MyChildAttribute1 = a1; MyChildAttribute2 = a2; } [ConfigurationProperty("myChildAttrib1", DefaultValue = "Zippy", IsRequired = true)] [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] public String MyChildAttribute1 { get { return (String)this["myChildAttrib1"]; } set { this["myChildAttrib1"] = value; } } [ConfigurationProperty("myChildAttrib2", DefaultValue = "Michael Zawondy", IsRequired = true)] [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] public String MyChildAttribute2 { get { return (String)this["myChildAttrib2"]; } set { this["myChildAttrib2"] = value; } } } }
This example uses the declarative model. The System.Configuration.ConfigurationSection class can also be implemented using the programmatic model. For an example, see the System.Configuration.ConfigurationSection class overview topic, and Classes Used to Create Custom Section Handlers.
For the purposes of comparison, this example is similar to the code in How to: Create Custom Configuration Sections Using IConfigurationSectionHandler. However, inheriting from the System.Configuration.ConfigurationSection class allows for finer control of your section handler. For example, the configuration file in the next procedure allows for a child element called
myChildSection
for which the preceding code declares a ConfigurationProperty and defines as a class derived from ConfigurationElement. Additionally, the encapsulation of collection functionality in the ConfigurationElementCollection class allows you to easily create collection elements that can employ add, remove, and clear elements in a configuration file. For more information and examples, see ConfigurationElementCollection.
To add a custom section handler to an ASP.NET configuration file
Add a sectionGroup element and a section element to your Web.config file inside the configSections element, as illustrated in the following code example. It is this declaration that associates the custom section handler with the section name.
Note Nesting a section element in a sectionGroup is optional, but it is recommended to help better organize configuration data.
You can add the section-handler declaration in a different configuration file than the one where you add your 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 type attribute of the section element must match the manifest of the assembly or there will be a configuration error. The assembly file itself must be in the same ASP.NET application directory as the Web.config file that defines it.
<configuration> <!-- Configuration section-handler declaration area. --> <configSections> <sectionGroup name="myCustomGroup"> <section name="myCustomSection" type="MyConfigSectionHandler.MyHandler, MyCustomConfigurationHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" /> </sectionGroup> <!-- Other <section> and <sectionGroup> elements. --> </configSections> <!-- Configuration section settings area. --> </configuration>
Add your custom configuration elements in the configuration section settings area of your Web.config file.
<configuration> <!-- Configuration section-handler declaration area. --> <!-- Configuration section settings area. --> <myCustomGroup> <myCustomSection myAttrib1="Clowns"> <myChildSection myChildAttrib1="Zippy" myChildAttrib2="Michael Zawondy "/> </myCustomSection> </myCustomGroup> <!-- Other configuration settings, like <system.web> --> </configuration>
To programmatically access your custom configuration data
Obtain an instance of your custom configuration object and use the GetSection method or the GetSection method to populate it.
The following example of an ASPX page works with the previous examples to enumerate the attributes and child elements of the custom configuration section.
<%@ Page Language="C#" %> <script runat="server"> protected void Button1_Click(object sender, EventArgs e) { MyConfigSectionHandler.MyHandler config = (MyConfigSectionHandler.MyHandler)System.Configuration.ConfigurationManager.GetSection( "myCustomGroup/myCustomSection"); StringBuilder sb = new StringBuilder(); sb.Append("<h2>Attributes in the myCustomSection Element:</h2>"); sb.AppendFormat("myAttrib1 = {0}<br/>", config.MyAttrib1.ToString()); sb.Append("<h2>Attributes in the myChildSection Element:</h2>"); sb.AppendFormat("myChildAttrib1 = {0}<br/>", config.MyChildSection.MyChildAttribute1.ToString()); sb.AppendFormat("myChildAttrib2 = {0}<br/>", config.MyChildSection.MyChildAttribute2.ToString()); Label1.Text = sb.ToString(); Label1.Visible = true; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <h1>Enumerate MyCustomSection</h1> <asp:Label ID="Label1" runat="server" Text="" /> <br /> <asp:Button ID="Button1" runat="server" Text="Get Custom Config Info" OnClick="Button1_Click" /> </div> </form> </body> </html>
<%@ 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 Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim config As New MyConfigSectionHandler.MyHandler config = _ System.Configuration.ConfigurationManager.GetSection("myCustomGroup/myCustomSection") Dim sb As New StringBuilder sb.Append("<h2>Attributes in the myCustomSection Element:</h2>") sb.AppendFormat("myAttrib1 = {0}<br/>", config.MyAttrib1.ToString()) sb.Append("<h2>Attributes in the myChildSection Element:</h2>") sb.AppendFormat("myChildAttrib1 = {0}<br/>", config.MyChildSection.MyChildAttribute1.ToString()) sb.AppendFormat("myChildAttrib2 = {0}<br/>", config.MyChildSection.MyChildAttribute2.ToString()) Label1.Text = sb.ToString() Label1.Visible = True End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <h1>Enumerate MyCustomSection</h1> <asp:Label ID="Label1" runat="server" Text=""/> <br /> <asp:Button ID="Button1" runat="server" Text="Get Custom Config Info" OnClick="Button1_Click" /> </div> </form> </body> </html>
See Also
Concepts
ASP.NET Configuration File Structure (Sections and Section Handlers)
ASP.NET Configuration Overview