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

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

.NET Framework 4
其他版本
此主题尚未评级 - 评价此主题

 

您可以用自己的 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 使用该配置对象,以对自定义配置元素进行读取和写入。

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

  1. 创建一个实现 System.Configuration.IConfigurationSectionHandler 接口的公共类,如下面的代码所示。

    C#
    VB
     
    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
      }
    }
    
    
    
  2. 添加您自己的代码,以执行所需的配置工作。

    例如,可以用获取 section 参数的 Attributes 属性的特性名和值的代码来替换 throw new Exception("The method is not implemented."); 行,并返回一个自定义配置对象。 下面的示例将 Hashtable 用作配置对象。

    C#
    VB
     
    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 配置文件添加自定义节处理程序

  1. sectionGroupsection 元素添加到 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>
    
  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>
    

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

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

    下面的 ASPX 页的示例使用前面的示例,以在单击按钮时枚举自定义配置节的特性和子元素。

    因为自定义节处理程序将 Hashtable 用作配置对象,所以 GetSection 方法返回 Hashtable

    下面的代码位于 .aspx 页中。 按钮单击事件的代码(位于代码隐藏文件中)包含在下一个代码示例中。

    下面的代码示例需要 .NET Framework 1.0 或 1.1 版。

    C#
     
    <%@ 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="http://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>
    
    VB
     
    <%@ 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="http://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;
    
            }
        }
    }
    

转载于:https://www.cnblogs.com/xust/articles/3287209.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值