使用組態類別

更新:2007 年 11 月

大部分組態工作都是使用 Configuration 類別 (Class) 完成的。這個類別表示電腦、.NET 用戶端應用程式、ASP.NET 應用程式、Web 目錄和儲存在 Web 目錄中之資源的組態。

在 ASP.NET 2.0 版中,您可以使用 WebConfigurationManager 物件的方法取得對 Configuration 類別之執行個體的存取,以取得組態區段 (在 .NET Framework 用戶端應用程式中,您可以使用類似的 ConfigurationManager 物件)。每個組態區段都有自己的物件型別,在 ASP.NET 組態設定之參考主題中的「項目資訊」表格內列示為區段處理常式。如需範例,請參閱 HOW TO:以程式設計方式存取 ASP.NET 組態設定

下列章節描述如何在不同的案例中使用組態類別。如需組態類別的摘要,請參閱 ASP.NET 組態 API 概觀

下面所有的範例都藉由首先建立 System.Configuration.Configuration 類別的執行個體,使用非靜態的 Configuration.GetSectionConfiguration.GetSectionGroup 方法。這可讓您從任何應用程式取得組態資訊。如果您要從程式碼所在的應用程式取得組態資訊,請使用靜態 (Static) GetSection 方法,這樣會處理得更快一些。如需詳細資訊,請參閱 ASP.NET 組態 API 概觀中的<使用本機和遠端組態設定>章節。

開啟對應至全域組態設定的組態物件

若要開啟全域組態的組態檔,您的應用程式會呼叫 WebConfigurationManager 類別的 OpenMachineConfiguration 靜態方法。在下列程式碼範例中,OpenMachineConfiguration 方法會開啟並傳回對應至 .NET Framework 2.0 之 Machine.config 檔的組態物件。這個多載方法的其他版本可讓您指定位置、遠端伺服器或使用者資訊。

' Obtains the machine configuration settings on the local machine.
Dim machineConfig As System.Configuration.Configuration
machineConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration()
machineConfig.SaveAs("c:\machineConfig.xml")
         // Obtains the machine configuration settings on the local machine.
            System.Configuration.Configuration machineConfig = 
                System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration();
            machineConfig.SaveAs("c:\\machineConfig.xml");

組態 API 是版本特定的。因此,無法使用某個版本 .NET Framework 中包含的方法開啟另一個版本 .NET Framework 中的 Machine.config 檔。

必要的權限

若要開啟電腦組態檔,應用程式需要實體 Machine.config 檔的讀取權限。若要修改電腦組態,應用程式需要檔案的寫入權限和 .NET Framework 組態目錄的建立權限。

開啟對應至 Web 應用程式組態設定的組態物件

若要開啟 Web 應用程式的組態檔,您的應用程式會呼叫 WebConfigurationManager 類別的 OpenWebConfiguration 靜態方法,並傳遞要開啟之網際網路資訊服務 (IIS) 虛擬目錄的相對路徑。

路徑參數的值可以從包含必要組態之目錄的 IIS Metabase 路徑中取得。例如,如果 IIS Metabase 路徑為 W3SVC/1/Root/Temp,則因為預設網站為 1,所以路徑為 /Temp。

在下列程式碼範例中,OpenWebConfiguration 方法會開啟並傳回對應至預設網站中 Temp Web 應用程式的組態物件。組態物件包括在本機 Web.config 檔中指定的組態設定,以及所有繼承自父組態檔 (一直到 Machine.config 檔) 的設定。這個多載方法的其他版本可讓您指定網站、位置、遠端伺服器和使用者資訊。

' Obtains the configuration settings for a Web application.
Dim webConfig As System.Configuration.Configuration
webConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp")
webConfig.SaveAs("c:\\webConfig.xml")
         // Obtains the configuration settings for a Web application.
            System.Configuration.Configuration webConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            webConfig.SaveAs("c:\\webConfig.xml");

即使在實體 Web.config 檔不存在的情況下,仍然可以開啟 System.Configuration.Configuration 物件。在這種情況下,傳回的組態便是繼承自組態檔階層架構的設定。如需詳細資訊,請參閱 ASP.NET 組態案例

必要的權限

若要開啟 Web 組態檔,應用程式需要實體 Web.config 檔和階層架構中其所有父組態檔的讀取權限。

開啟對應至組態檔中區段的組態物件

若要從區段取得組態資訊,您的應用程式會呼叫 Configuration 類別的 GetSectionGroup 非靜態方法,並傳遞區段名稱。如需包含在區段群組中的區段,您可以使用區段的 XPath (system.web/anonymousIdentification),或取得已對應至區段群組的組態物件。如需區段名稱的清單,請參閱 ASP.NET 組態設定

在下列程式碼範例中,OpenWebConfiguration 方法會開啟並傳回對應至預設網站中 Temp Web 應用程式的組態物件,然後使用該物件取得 system.web 區段群組的參考,接著使用該參考取得 anonymousIdentification 區段的參考。

' Obtains the configuration settings for the <anonymousIdentification> section.
Dim config As System.Configuration.Configuration
config = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp")
Dim systemWeb As System.Web.Configuration.SystemWebSectionGroup
systemWeb = config.GetSectionGroup("system.web")
Dim sectionConfig As System.Web.Configuration.AnonymousIdentificationSection
sectionConfig = systemWeb.AnonymousIdentification
Dim sb As New StringBuilder
sb.AppendLine("<anonymousIdentification> attributes:")
Dim props As System.Configuration.PropertyInformationCollection
props = sectionConfig.ElementInformation.Properties
For Each prop As System.Configuration.PropertyInformation In props
    sb.Append(prop.Name.ToString())
    sb.Append(" = ")
    sb.AppendLine(prop.Value.ToString())
Next
Console.WriteLine(sb.ToString())
         // Obtains the configuration settings for the <anonymousIdentification> section.
            System.Configuration.Configuration config =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            System.Web.Configuration.SystemWebSectionGroup systemWeb =
                config.GetSectionGroup("system.web") 
                as System.Web.Configuration.SystemWebSectionGroup;
            System.Web.Configuration.AnonymousIdentificationSection sectionConfig =
                systemWeb.AnonymousIdentification;
            if (null != sectionConfig)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<anonymousIdentification> attributes:\r\n");
                System.Configuration.PropertyInformationCollection props =
                    sectionConfig.ElementInformation.Properties;
                foreach (System.Configuration.PropertyInformation prop in props)
                {
                    sb.AppendFormat("{0} = {1}\r\n", prop.Name.ToString(), prop.Value.ToString());
                }
                Console.WriteLine(sb.ToString());
            }

即使在實體 Web.config 檔不存在的情況下,仍然可以開啟 System.Configuration.Configuration 物件。在這種情況下,傳回的組態包括整個繼承自組態檔階層架構的設定。如需詳細資訊,請參閱 ASP.NET 組態案例

必要的權限

若要開啟 Web 組態檔中的區段,應用程式需要實體 Web.config 檔和階層架構中其所有父組態檔的讀取權限。Managed 程式碼應用程式需要具有讀取系統區段的權限。根據預設,完全信任和高度信任應用程式具有這些使用權限。也就是說,根據預設,中度和低度信任的應用程式將無法讀取組態區段。

開啟對應至遠端組態設定的組態物件

您可以使用組態 API 開啟遠端電腦的組態。API 可以開啟其他電腦的電腦組態檔,或者任何 IIS 應用程式或其子目錄的應用程式組態檔。

若要開啟其他電腦上的電腦組態檔,應用程式會呼叫 OpenMachineConfiguration 靜態方法,並傳遞伺服器的名稱。

若要開啟其他電腦上的 Web.config 檔,應用程式會呼叫 OpenWebConfiguration 靜態方法,並傳遞組態物件的網站相對路徑、網站識別項和伺服器的名稱。傳回的組態物件包括在本機 Web.config 檔中指定的組態設定,以及所有繼承自父組態檔 (一直到 Machine.config 檔) 的設定。

伺服器名稱是有效的 Windows 網路電腦名稱。這些名稱不是專門由 ASP.NET 處理,但是會直接傳遞至作業系統。

在下列程式碼中,示範了如何開啟電腦組態、預設網站上的根組態和應用程式目錄中的 Web 組態。

Dim userToken As IntPtr
userToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token

' Obtains the machine configuration settings on a remote machine.
Dim remoteMachineConfig As System.Configuration.Configuration
remoteMachineConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration( _
    Nothing, "JanetFi2", userToken)
remoteMachineConfig.SaveAs("c:\remoteMachineConfig.xml")

' Obtains the root Web configuration settings on a remote machine.
Dim remoteRootConfig As System.Configuration.Configuration
remoteRootConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration( _
    Nothing, Nothing, Nothing, "JanetFi2", userToken)
remoteRootConfig.SaveAs("c:\remoteRootConfig.xml")

' Obtains the configuration settings for the 
' W3SVC/1/Root/Temp application on a remote machine.
Dim remoteWebConfig As System.Configuration.Configuration
remoteWebConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration( _
    "/Temp", "1", Nothing, "JanetFi2", userToken)
remoteWebConfig.SaveAs("c:\\remoteWebConfig.xml")
         IntPtr userToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token;

            // Obtains the machine configuration settings on a remote machine.
            System.Configuration.Configuration remoteMachineConfig =
                System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration
                (null, "ServerName", userToken);
            remoteMachineConfig.SaveAs("c:\\remoteMachineConfig.xml");

            // Obtains the root Web configuration settings on a remote machine.
            System.Configuration.Configuration remoteRootConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
                (null, null, null, "ServerName", userToken);
            remoteRootConfig.SaveAs("c:\\remoteRootConfig.xml");

            // Obtains the configuration settings for the 
            // W3SVC/1/Root/Temp application on a remote machine.
            System.Configuration.Configuration remoteWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
                ("/Temp", "1", null, "ServerName", userToken);
            remoteWebConfig.SaveAs("c:\\remoteWebConfig.xml");

必要的權限

若要開啟遠端電腦上的組態檔,應用程式必須具有遠端電腦上的系統管理權限。這個需要比本機用法的需要更嚴格。若為本機組態檔,應用程式只需要階層架構中組態檔以及 IIS Metabase (用於解析 IIS 路徑) 的讀取權限。

在嘗試設定之前,先在遠端電腦上使用 "-config+" 參數執行 Aspnet_regiis.exe 工具。如需詳細資訊,請參閱 ASP.NET IIS 註冊工具 (Aspnet_regiis.exe)

更新組態設定

若要更新開啟的組態物件,應用程式會呼叫組態物件的 SaveSaveAs 方法。這些方法會寫入該物件的任何組態設定變更。如果該位置上不存在組態檔,則會建立新的組態檔。

下列程式碼範例會將編譯 (Compilation) 區段的 debug 屬性 (Attribute) 設為 true。

' Updates the configuration settings for a Web application.
Dim updateWebConfig As System.Configuration.Configuration
updateWebConfig = _
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp")
Dim compilation As System.Web.Configuration.CompilationSection
compilation = _
    updateWebConfig.GetSection("system.web/compilation")
Console.WriteLine("Current <compilation> debug = {0}", compilation.Debug)
compilation.Debug = True
If Not compilation.SectionInformation.IsLocked Then
    updateWebConfig.Save()
    Console.WriteLine("New <compilation> debug = {0}", compilation.Debug)
Else
    Console.WriteLine("Could not save configuration.")
End If
         // Updates the configuration settings for a Web application.
            System.Configuration.Configuration updateWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            System.Web.Configuration.CompilationSection compilation =
                updateWebConfig.GetSection("system.web/compilation") 
                as System.Web.Configuration.CompilationSection;
            Console.WriteLine("Current <compilation> debug = {0}", compilation.Debug);
            compilation.Debug = true;
            if (!compilation.SectionInformation.IsLocked)
            {
                updateWebConfig.Save();
                Console.WriteLine("New <compilation> debug = {0}", compilation.Debug);
            }
            else
            {
                Console.WriteLine("Could not save configuration.");
            }

目前,沒有任何可在更新組態資料時鎖定它的功能。因此,組態 API 會使用開放式並行存取 (Optimistic Concurrency) 模型以修改組態。在開放式並行存取模型下,如果兩個應用程式同時開啟相同的組態,則它們會取得組態物件的相同複本。如果應用程式嘗試藉由呼叫 SaveSaveAs 方法修改組態,而且基礎組態檔自應用程式取得組態物件後已進行修改,則該方法會引發例外狀況。基礎檔案可能已由其他應用程式進行更新組態,或由不依賴於組態 API 的一些其他檔案修改而變更。

必要的權限

若要修改 Web 組態,應用程式需要檔案的寫入權限和包含該檔案之目錄的建立權限。

請參閱

概念

ASP.NET 組態 API 概觀

其他資源

ASP.NET 組態設定