如何:使用 ConfigurationSection 创建自定义配置节

更新:2007 年 11 月

您可以用自己的 XML 配置元素来扩展标准的 ASP.NET 配置设置集。若要完成该操作,您必须创建自己的配置节处理程序。

该处理程序必须是一个用来实现 System.Configuration.ConfigurationSection 类的 .NET Framework 类。

2tw134k3.alert_note(zh-cn,VS.90).gif说明:

在 .NET Framework 1.0 和 1.1 版中,配置节处理程序必须实现 System.Configuration.IConfigurationSectionHandler 接口,该接口现在已被否决。但是,代码示例存在于如何:使用 IConfigurationSectionHandler 创建自定义配置节中。

节处理程序解释并处理 Web.config 文件特定部分中 XML 配置元素中定义的设置,并根据配置设置返回适当的配置对象。处理程序类返回的配置对象可以是任何数据结构;它不限于任何基配置类或配置格式。ASP.NET 使用该配置对象,以对自定义配置元素进行读取和写入。

创建自定义配置节处理程序

  1. 创建一个继承 System.Configuration.ConfigurationSection 类的公共类,如下面的代码示例所示。

    Imports System
    Imports System.Collections
    Imports System.Text
    Imports System.Configuration
    Imports System.Xml
    
    Namespace MyConfigSectionHandler
    
        Public Class MyHandler
            Inherits ConfigurationSection
    
            Public Sub New()
            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; }
            // }
        }
    }
    
  2. 添加您自己的代码,以执行所需的配置工作。

    例如,可以将注释代码替换为下面的代码,下面的代码从自定义节中获取值。

    Imports System
    Imports System.Collections
    Imports System.Text
    Imports System.Configuration
    Imports System.Xml
    
    Namespace MyConfigSectionHandler
    
        Public Class MyHandler
            Inherits ConfigurationSection
    
            Public Sub New()
            End Sub
    
            Public Sub New(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 New()
            End Sub
    
            Public Sub New( _
            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; }
            }
        }
    }
    

    此示例使用声明性模型。System.Configuration.ConfigurationSection 类还可以通过使用编程模型来实现。有关示例,请参见 System.Configuration.ConfigurationSection 类概述主题以及用于创建自定义节处理程序的类

    为了进行比较,此示例类似于如何:使用 IConfigurationSectionHandler 创建自定义配置节中的代码。但是,从 System.Configuration.ConfigurationSection 类继承允许对节处理程序进行更精细的控制。例如,下一个过程中的配置文件允许使用一个名为 myChildSection 的子元素,在上面的代码中,为该子元素声明了 ConfigurationProperty)并将该属性定义为从 ConfigurationElement 派生的类。另外,如果将集合功能封装在 ConfigurationElementCollection 类中,则可以方便地创建能够利用配置文件中 add、remove 和 clear 元素的集合元素。有关更多信息和示例,请参见 ConfigurationElementCollection

向 ASP.NET 配置文件添加自定义节处理程序

  1. sectionGroup 元素和 section 元素添加到 Web.config 文件的 configSections 元素中,如下面的代码示例所示。正是此声明将自定义节处理程序与节名关联。

    2tw134k3.alert_note(zh-cn,VS.90).gif说明:

    将 section 元素嵌套在 sectionGroup 中是可选的,但是建议这样做,以便更好地组织配置数据。

    可以在另一个配置文件中添加节处理程序声明,该配置文件不必是添加自定义配置元素的配置文件,只要声明节处理程序的配置文件在配置文件的层次结构中位于较高的位置。有关更多信息,请参见 ASP.NET 配置文件层次结构和继承

    section 元素的 type 属性必须与程序集清单匹配,否则将出现配置错误。程序集文件必须与定义它的 Web.config 文件位于相同的 ASP.NET 应用程序目录。

    <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>
    
  2. 在 Web.config 文件的配置节设置区域中添加自定义配置元素。

    <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>
    

以编程方式访问自定义配置数据

  • 获取自定义配置对象的一个实例,并使用 GetSection 方法或 GetSection 方法来填充该实例。

    下面的 ASPX 页的示例使用前一个示例,以枚举自定义配置节的属性和子元素。

    <%@ 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>
    

请参见

概念

ASP.NET 配置文件结构(节和节处理程序)

ASP.NET 配置概述

其他资源

管理 ASP.NET 网站

配置应用程序