HOW TO:使用 ConfigurationSection 建立自訂組態區段
更新:2007 年 11 月
您可以使用自己的 XML 組態項目,來擴充一組標準的 ASP.NET 組態設定。若要執行這項作業,您必須建立自己的組態區段處理常式。
處理常式必須是實作 System.Configuration.ConfigurationSection 類別的 .NET Framework 類別。
注意事項: |
---|
在 .NET Framework 1.0 和 1.1 版中,組態區段處理常式必須實作 System.Configuration.IConfigurationSectionHandler 介面,現在這點已被取代。不過,HOW TO:使用 IConfigurationSectionHandler 建立自訂組態區段中仍有程式碼範例可供參考。 |
區段處理常式會解譯並處理 Web.config 檔特定部分內 XML 組態項目中定義的設定,並根據組態設定傳回適當的組態物件。處理常式類別傳回的組態物件可以是任何資料結構,不受任何基底組態類別或組態格式限制。ASP.NET 使用組態物件讀寫您自訂的組態項目。
若要建立自訂的組態區段處理常式
請依照下列程式碼範例所示,建立繼承 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; } // } } }
加入您自己的程式碼,以執行所需的組態工作。
例如,您可以用下列的程式碼 (會從自訂區段取得值),取代註解的程式碼。
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 類別概觀主題以及用來建立自訂區段處理常式的類別。
為了進行比較,這個範例與 HOW TO:使用 IConfigurationSectionHandler 建立自訂組態區段中的程式碼很類似。不過,如果繼承自 System.Configuration.ConfigurationSection 類別可以對區段處理常式進行更細微的控制。例如,下一個程序中的組態檔擁有一個稱為 myChildSection 的子項目,上述的程式碼為此項目宣告了 ConfigurationProperty,且將其定義為衍生自 ConfigurationElement 的類別。此外,ConfigurationElementCollection 類別中的集合功能封裝 (Encapsulation) 可以用來輕鬆建立集合項目,以在組態檔中運用加入、移除和清除項目。如需詳細資訊與範例,請參閱ConfigurationElementCollection。
若要將自訂的區段處理常式加入至 ASP.NET 組態檔
將 sectionGroup 項目和 section 項目加入至 configSections 項目內的 Web.config 檔案,如下列的程式碼範例所示。這個宣告會在自訂的區段處理常式和區段名稱之間建立關聯。
注意事項: 您可選擇是否將 section 項目套疊於 sectionGroup,但是建議您這麼做,以改善組態資料的組織。
只要宣告區段處理常式的組態檔擁有較高的組態檔階層架構位置,您就可以在其中加入自訂組態項目的組態檔以外的組態檔中,加入區段處理常式宣告。如需詳細資訊,請參閱 ASP.NET 組態檔階層架構和繼承。
section 項目的 type 屬性 (Attribute) 必須符合組件資訊清單 (Assembly Manifest),否則將會發生組態錯誤。組件檔本身必須與定義它的 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>
若要以程式設計的方式存取自訂組態資料
取得自訂組態物件的執行個體,然後使用 GetSection 方法或 GetSection 方法進行填入 (Populate)。
下列的 ASPX 頁面範例可用於前述範例,列舉出自訂組態區段的屬性和子項目。
<%@ Page Language="C#" %> <script > 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 > <title>Untitled Page</title> </head> <body> <form id="form1" > <div> <h1>Enumerate MyCustomSection</h1> <asp:Label ID="Label1" Text="" /> <br /> <asp:Button ID="Button1" 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 > 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 > <title>Untitled Page</title> </head> <body> <form id="form1" > <div> <h1>Enumerate MyCustomSection</h1> <asp:Label ID="Label1" Text=""/> <br /> <asp:Button ID="Button1" Text="Get Custom Config Info" OnClick="Button1_Click" /> </div> </form> </body> </html>