如何:使用 IConfigurationSectionHandler 创建自定义配置节
更新:2007 年 11 月
您可以用自己的 XML 配置元素来扩展标准的 ASP.NET 配置设置集。若要完成该操作,您必须创建自己的配置节处理程序。
该处理程序必须是一个实现 System.Configuration.IConfigurationSectionHandler 接口或 System.Configuration.ConfigurationSection 类的 .NET Framework 类。
说明: |
---|
此主题使用 System.Configuration.IConfigurationSectionHandler 接口,该接口在 .NET Framework 2.0 版中已被否决。有关使用 System.Configuration.ConfigurationSection 类的示例,请参见如何:使用 ConfigurationSection 创建自定义配置节。如果使用下面的代码示例,请使用 .NET Framework 1.0 或 1.1 版生成它们。 |
节处理程序解释并处理 Web.config 文件特定部分中 XML 配置元素中定义的设置,并根据配置设置返回适当的配置对象。处理程序类返回的配置对象可以是任何数据结构;它不限于任何基配置类或配置格式。ASP.NET 使用该配置对象,以对自定义配置元素进行读取和写入。
创建自定义配置节处理程序
创建一个实现 System.Configuration.IConfigurationSectionHandler 接口的公共类,如下面的代码所示。
Imports System Imports System.Collections Imports System.Text Imports System.Configuration Imports System.Xml Namespace MyConfigSectionHandler Public Class MyHandler 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 Throw New System.Exception("The method is not implemented.") End Function End Class End Namespace
using System; using System.Collections.Generic; using System.Text; using System.Configuration; using System.Xml; namespace MyConfigSectionHandler { public class MyHandler : IConfigurationSectionHandler { #region IConfigurationSectionHandler Members object IConfigurationSectionHandler.Create( object parent, object configContext, XmlNode section) { throw new Exception("The method is not implemented."); } #endregion } }
添加您自己的代码,以执行所需的配置工作。
例如,可以用获取 section 参数的 Attributes 属性的属性名和值的代码来替换 throw new Exception("The method is not implemented."); 行,并返回一个自定义配置对象。下面的示例将 Hashtable 用作配置对象。
Imports System Imports System.Collections Imports System.Text Imports System.Configuration Imports System.Xml Namespace MyConfigSectionHandler Public Class MyHandler 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 ' Creates the configuration object that this method will return. ' This can be a custom configuration class. ' In this example, we use a System.Collections.Hashtable. Dim myConfigObject As New Hashtable ' Gets any attributes for this section element. Dim myAttribs As New Hashtable For Each attrib As XmlAttribute In section.Attributes If XmlNodeType.Attribute = attrib.NodeType Then myAttribs.Add(attrib.Name, attrib.Value) End If Next ' Puts the section name and attributes as the first config object item. myConfigObject.Add(section.Name, myAttribs) ' Gets the child element names and attributes. For Each child As XmlNode In section.ChildNodes If XmlNodeType.Element = child.NodeType Then Dim myChildAttribs As New Hashtable For Each childAttrib As XmlAttribute In child.Attributes If XmlNodeType.Attribute = childAttrib.NodeType Then myChildAttribs.Add(childAttrib.Name, childAttrib.Value) End If Next myConfigObject.Add(child.Name, myChildAttribs) End If Next Return (myConfigObject) End Function End Class End Namespace
using System; using System.Collections; using System.Text; using System.Configuration; using System.Xml; namespace MyConfigSectionHandler { public class MyHandler : IConfigurationSectionHandler { #region IConfigurationSectionHandler Members object IConfigurationSectionHandler.Create( object parent, object configContext, XmlNode section) { // Creates the configuration object that this method will return. // This can be a custom configuration class. // In this example, we use a System.Collections.Hashtable. Hashtable myConfigObject = new Hashtable(); // Gets any attributes for this section element. Hashtable myAttribs = new Hashtable(); foreach (XmlAttribute attrib in section.Attributes) { if (XmlNodeType.Attribute == attrib.NodeType) myAttribs.Add(attrib.Name, attrib.Value); } // Puts the section name and attributes as the first config object item. myConfigObject.Add(section.Name, myAttribs); // Gets the child element names and attributes. foreach (XmlNode child in section.ChildNodes) { if (XmlNodeType.Element == child.NodeType) { Hashtable myChildAttribs = new Hashtable(); foreach (XmlAttribute childAttrib in child.Attributes) { if (XmlNodeType.Attribute == childAttrib.NodeType) myChildAttribs.Add(childAttrib.Name, childAttrib.Value); } myConfigObject.Add(child.Name, myChildAttribs); } } return (myConfigObject); } #endregion } }
向 ASP.NET 配置文件添加自定义节处理程序
将 sectionGroup 和 section 元素添加到 Web.config 文件的 configSections 元素中,如下面的代码所示。
说明: 在 sectionGroup 中嵌套 section 元素是可选的,但建议这样做以助于组织配置数据。
可以在另一个配置文件中添加节处理程序声明,该配置文件不必是添加自定义配置元素的配置文件,只要声明节处理程序的配置文件在配置文件的层次结构中位于较高的位置。有关更多信息,请参见 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>
在 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>
以编程方式访问自定义配置数据
获取自定义配置对象的一个实例,并使用 ConfigurationManager.GetSection 方法或 WebConfigurationManager.GetSection 方法来填充该实例。
下面的 ASPX 页的示例使用前面的示例,以在单击按钮时枚举自定义配置节的属性和子元素。
因为自定义节处理程序将 Hashtable 用作配置对象,所以 GetSection 方法返回 Hashtable。
下面的代码位于 .aspx 页中。按钮单击事件的代码(位于代码隐藏文件中)包含在下一个代码示例中。
下面的代码示例需要 .NET Framework 1.0 或 1.1 版。
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="BugTest.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <html> <head> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 2003"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema content="https://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <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" /> </form> </body> </html>
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 2003"> <meta name="CODE_LANGUAGE" Content="VB"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="https://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <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" /> </form> </body> </HTML>
下面的按钮单击事件代码在属于上述 .aspx 页的代码隐藏文件中。该代码隐藏文件使用 .aspx.cs 或 .aspx.vb 的文件扩展名,具体取决于 @Page 声明的 language 属性。
[C#]
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Configuration; using System.Text; namespace BugTest { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Button Button1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Button1.Click += new System.EventHandler(this.Button1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion protected void Button1_Click(object sender, System.EventArgs e) { Hashtable config = (Hashtable)System.Configuration.ConfigurationSettings.GetConfig("myCustomGroup/myCustomSection"); StringBuilder sb = new StringBuilder(); sb.AppendFormat("Config object item count = {0}<br/><br/>", config.Count); foreach (DictionaryEntry deKey in config) { sb.AppendFormat("<h2>Attributes in the {0} Element:</h2>", deKey.Key.ToString()); Hashtable attribs = (Hashtable)deKey.Value; foreach (DictionaryEntry deAttrib in attribs) { sb.AppendFormat("{0} = {1}<br/>", deAttrib.Key.ToString(), deAttrib.Value.ToString()); } } Label1.Text = sb.ToString(); Label1.Visible = true; } } }
Imports System.Text Public Class WebForm1 Inherits System.Web.UI.Page #Region " Web Form Designer Generated Code " 'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() End Sub Protected WithEvents Label1 As System.Web.UI.WebControls.Label Protected WithEvents Button1 As System.Web.UI.WebControls.Button 'NOTE: The following placeholder declaration is required by ' the Web Form Designer. 'Do not delete or move it. Private designerPlaceholderDeclaration As System.Object Private Sub Page_Init(ByVal sender As System.Object, ByVal _ e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region Private Sub Page_Load(ByVal sender As System.Object, ByVal _ e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here End Sub Protected Sub Button1_Click(ByVal sender As System.Object, ByVal _ e As System.EventArgs) Handles Button1.Click Dim config As Hashtable = _ System.Configuration.ConfigurationSettings.GetConfig( _ "myCustomGroup/myCustomSection") Dim sb As New StringBuilder sb.AppendFormat("Config object item count = {0}<br/><br/>", _ config.Count) For Each deKey As DictionaryEntry In config sb.AppendFormat("<h2>Attributes in the {0} Element:</h2>", _ deKey.Key.ToString()) Dim attribs As Hashtable = deKey.Value For Each deAttrib As DictionaryEntry In attribs sb.AppendFormat("{0} = {1}<br/>", deAttrib.Key.ToString(), _ deAttrib.Value.ToString()) Next Label1.Text = sb.ToString() Label1.Visible = True Next End Sub End Class
请参见
任务
如何:使用 ConfigurationSection 创建自定义配置节