如何:使用 IConfigurationSectionHandler 创建自定义配置节
摘要:您可以用自己的 XML 配置元素来扩展标准的 ASP.NET 配置设置集。若要完成该操作,您必须创建自己的配置节处理程序。该处理程序必须是一个实现 System.Configuration.IConfigurationSectionHandler 接口或 System.Configuration.ConfigurationSection 类的 .NET Framework 类。
此主题使用 System.Configuration.IConfigurationSectionHandler 接口,该接口在 .NET Framework 2.0 版中已被否决。有关使用 System.Configuration.ConfigurationSection 类的示例
节处理程序解释并处理 Web.config 文件特定部分中 XML 配置元素中定义的设置,并根据配置设置返回适当的配置对象。处理程序类返回的配置对象可以是任何数据结构;它不限于任何基配置类或配置格式。ASP.NET 使用该配置对象,以对自定义配置元素进行读取和写入。
1. 创建自定义配置节处理程序
创建一个实现 System.Configuration.IConfigurationSectionHandler 接口的公共类,添加您自己的代码,以执行所需的配置工作。例如,可以用获取 section 参数的 Attributes 属性的属性名和值的代码来替换 throw new Exception("The method is not implemented."); 行,并返回一个自定义配置对象。下面的示例将 Hashtable 用作配置对象。如下面的代码所示:
using System;
using System.Collections;
using System.Text;
using System.Configuration;
using System.Xml;
namespace WebConfigApp
{
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
}
}
2. 向 ASP.NET 配置文件添加自定义节处理程序
将 sectionGroup 和 section 元素添加到 Web.config 文件的 configSections 元素中,如下面的添加代码所示(红色字体)
注意:在 sectionGroup 中嵌套 section 元素是可选的,但建议这样做以助于组织配置数据。可以在另一个配置文件中添加节处理程序声明,该配置文件不必是添加自定义配置元素的配置文件,只要声明节处理程序的配置文件在配置文件的层次结构中位于较高的位置。有关更多信息,请参见 ASP.NET 配置文件层次结构和继承。
section 元素的 type 属性必须与程序集清单匹配,否则将出现配置错误。程序集文件必须与定义它的 Web.config 文件位于相同的 ASP.NET 应用程序目录。
在 Web.config 文件的配置节设置区域中添加自定义配置元素(绿色字体)。
<configuration>
<configSections>
<sectionGroup name="myCustomGroup">
<section
name="myCustomSection"
type="WebConfigApp.MyHandler, WebConfigApp, Version= 1.0.0 .0, Culture=neutral, PublicKeyToken=null"
allowLocation="true"
allowDefinition="Everywhere"
/>
</sectionGroup>
</configSections>
<myCustomGroup>
<myCustomSection myAttrib1="Clowns">
<myChildSection
myChildAttrib1="Zippy"
myChildAttrib2="Michael Zawondy "/>
</myCustomSection>
</myCustomGroup>
<!—省略-->
</configuration>
3. 以编程方式访问自定义配置数据
下面的 ASPX 页的示例使用前面的示例,以在单击按钮时枚举自定义配置节的属性和子元素。因为自定义节处理程序将 Hashtable 用作配置对象,所以 GetSection 方法返回 Hashtable。下面的代码位于 .aspx 页中。按钮单击事件的代码(位于代码隐藏文件中)包含在下一个代码示例中。
下面的代码示例需要 .NET Framework 1.0 或 1.1 版。
aspx页面部分代码:
<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>
aspx.cs代码:
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;
}
注意命名空间的引用:
using System.Configuration;
using System.Text;
如何:使用 ConfigurationSection 创建自定义配置节
您可以用自己的 XML 配置元素来扩展标准的 ASP.NET 配置设置集。若要完成该操作,您必须创建自己的配置节处理程序。该处理程序必须是一个用来实现 System.Configuration.ConfigurationSection 类的 .NET Framework 类。
节处理程序解释并处理 Web.config 文件特定部分中 XML 配置元素中定义的设置,并根据配置设置返回适当的配置对象。处理程序类返回的配置对象可以是任何数据结构;它不限于任何基配置类或配置格式。ASP.NET 使用该配置对象,以对自定义配置元素进行读取和写入。
1. 创建自定义配置节处理程序
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
2. 向 ASP.NET 配置文件添加自定义节处理程序
<configuration>
<configSections>
<sectionGroup name="myCustomGroup">
<section
name="myCustomSection"
type="WebConfigApp.MyHandler, WebConfigApp, Version= 1.0.0 .0, Culture=neutral, PublicKeyToken=null"
allowLocation="true"
allowDefinition="Everywhere"
/>
</sectionGroup>
</configSections>
<myCustomGroup>
<myCustomSection myAttrib1="Clowns">
<myChildSection
myChildAttrib1="Zippy"
myChildAttrib2="Michael Zawondy "/>
</myCustomSection>
</myCustomGroup>
<!—省略-->
</configuration>
将 sectionGroup 元素和 section 元素添加到 Web.config 文件的 configSections 元素中,如下面的代码示例所示。正是此声明将自定义节处理程序与节名关联。可以在另一个配置文件中添加节处理程序声明,该配置文件不必是添加自定义配置元素的配置文件,只要声明节处理程序的配置文件在配置文件的层次结构中位于较高的位置。有关更多信息,请参见 ASP.NET 配置文件层次结构和继承。
section 元素的 type 属性必须与程序集清单匹配,否则将出现配置错误。程序集文件必须与定义它的 Web.config 文件位于相同的 ASP.NET 应用程序目录。
3. 以编程方式访问自定义配置数据
获取自定义配置对象的一个实例,并使用 GetSection 方法或 GetSection 方法来填充该实例。下面的 ASPX 页的示例使用前一个示例,以枚举自定义配置节的属性和子元素。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W 3C //DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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 id="Head1" 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>