Share via


HOW TO:使用 IConfigurationSectionHandler 建立自訂組態區段

更新:2007 年 11 月

您可以使用自己的 XML 組態項目,來擴充一組標準的 ASP.NET 組態設定。若要執行這項作業,您必須建立自己的組態區段處理常式。

該處理常式必須是實作 System.Configuration.IConfigurationSectionHandler 介面或 System.Configuration.ConfigurationSection 類別的 .NET Framework 類別。

注意事項:

本主題使用 System.Configuration.IConfigurationSectionHandler 介面,該介面在 .NET Framework 2.0 版中已被取代。如需使用 System.Configuration.ConfigurationSection 類別的範例,請參閱 HOW TO:使用 ConfigurationSection 建立自訂組態區段。如果您使用下列程式碼範例,請利用 .NET Framework 1.0 或 1.1 版建置它們。

區段處理常式會解譯並處理在 Web.config 檔特定部分內 XML 組態項目中定義的設定,並根據組態設定傳回適當的組態物件。處理常式類別傳回的組態物件可以是任何資料結構,不受任何基底組態類別或組態格式限制。ASP.NET 使用組態物件讀取和寫入您的自訂組態項目。

若要建立自訂組態區段處理常式

  1. 建立實作 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
      }
    }
    
  2. 加入您自己的程式碼以執行需要的組態工作。

    例如,您可以使用從 section 參數的 Attributes 屬性 (Property) 取得屬性 (Attribute) 名稱和屬性值的程式碼,取代 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 組態檔

  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 網頁中。進入程式碼後置 (Code-Behind) 檔案之按鈕點選事件的程式碼會包含在下一個程式碼範例。

    下列程式碼範例必須有 .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" >
        <h1>Enumerate MyCustomSection</h1>
        <asp:Label ID="Label1"  
            Text="" />
        <br />
        <asp:Button ID="Button1"  
            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" >
          <h1>Enumerate MyCustomSection</h1>
          <asp:Label ID="Label1"  Text="" />
          <br>
          <asp:Button ID="Button1"  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
    

請參閱

工作

HOW TO:使用 ConfigurationSection 建立自訂組態區段

概念

ASP.NET 組態檔結構 (區段和區段處理常式)

其他資源

管理 ASP.NET 網站

管理 ASP.NET 網站

設定應用程式