共用方式為


HOW TO:遠端存取及修改 ASP.NET 組態檔

更新:2007 年 11 月

System.ConfigurationSystem.Web.Configuration 型別可讓您的應用程式存取遠端伺服器上的組態檔。特別是,您可以在遠端伺服器上的任何 Microsoft Internet Information Services (IIS) 應用程式或它的子目錄中開啟和修改 Machine.config 或 Web.config 檔。這個主題將:

  • 示範如何設定遠端伺服器,讓用戶端電腦得以存取伺服器組態檔。

  • 提供主控台應用程式以便在用戶端電腦上執行,該應用程式可以讀取或修改伺服器組態檔。

  • 討論要考慮的安全性考量。

若要存取遠端伺服器上的組態檔,用戶端電腦必須能與伺服器通訊。若要啟用此通訊,伺服器上必須安裝遠端組態元件。

然後,用戶端電腦會透過遠端組態元件呼叫 ASP.NET 組態 API,藉此存取伺服器組態檔。如需詳細資訊,請參閱編輯 ASP.NET 遠端組態檔

注意事項:

如果所要求的組態檔不存在,則正在伺服器上執行的 .NET Framework 會傳回一個組態檔,其內容完全由套用至指定路徑的繼承設定所組成。如果您的應用程式要求更新,則會建立一個新檔案。在執行主控台應用程式時,您必須輸入有效的伺服器名稱。這是因為 ASP.NET 會直接將此名稱傳遞給作業系統。因此,您必須輸入包含網域名稱前置字元的完整使用者名稱。

若要設定遠端伺服器

  1. 使用 ASP.NET IIS 註冊工具 (Aspnet_regiis.exe) 搭配 config+ 命令,在伺服器上安裝遠端組態元件,如下列程式碼所示:

    Aspnet_regiis config+
    
  2. 以程式設計方式或手動確認 IIS 伺服器「預設的網站」的 Web.config 檔包含類似下列的值:

    <appSettings>
        <add key="keyName1", value = "this entry value"/>
        <add key="keyName2", value = "this entry value"/>
        <add key="keyName3", value = "this entry value"/>
    </appSettings>
    

若要使用主控台應用程式更新遠端組態檔

  • 執行下列程式碼範例中所提供的主控台應用程式,以更新遠端伺服器上「預設的網站」的 Web.config 檔。此範例假設執行用戶端應用程式的使用者在遠端伺服器上具有系統管理員的權限。您可以使用這兩個命令中的其中一個。

    >remoteconfiguration machineName
    >remoteconfiguration machineName domainName\userName password
    

範例

Imports System
Imports System.Configuration
Imports System.Web.Configuration
Imports System.Collections.Specialized


' This example dDemonstrates how to access and modify remote 
' configuration files


Public Class RemoteConfiguration


    ' The application entry point.
    Public Shared Sub Main(ByVal args() As String) 

        ' This string  contains the name of 
        ' the remote server.
        Dim machineName As String = String.Empty

        ' Get the user's input.
        If args.Length > 0 Then
            ' Get the name of the remote server.
            ' The machine name must be in the format
            ' accepted by the operating system.
            machineName = args(0)

            ' Get the user name and password.
            If args.Length > 1 Then
                Dim userName As String = args(1)
                Dim password As String = String.Empty
                If args.Length > 2 Then
                    password = args(2)
                End If 
                ' Update the site configuration.
                UpdateConfiguration(machineName, userName, password)
            Else
                ' Update the site configuration.
                UpdateConfiguration(machineName)
            End If
        Else
            Console.WriteLine("Enter a valid server name.")
        End If

    End Sub 'Main


    ' Update the configuration file using the credentials
    ' of the user running this application. Tthen,
    ' call the routine that reads the configuration 
    ' settings.
    ' Note that the system issues an error if the user
    ' does not have administrative privileges on the server.
    Public Overloads Shared Sub _
    UpdateConfiguration(ByVal machineName As String)
        Try
            Console.WriteLine("MachineName:  [{0}]", machineName)
            Console.WriteLine("UserDomainName:  [{0}]", _
                Environment.UserDomainName)
            Console.WriteLine("UserName:  [{0}]", _
                Environment.UserName)

            ' Get the configuration.
            Dim config As Configuration = _
                WebConfigurationManager.OpenWebConfiguration("/", _
                "Default Web Site", Nothing, machineName)

            ' Add a new key/value pair to appSettings.
            Dim count As String = _
                config.AppSettings.Settings.Count.ToString()
            config.AppSettings.Settings.Add("key_" + count, _
                "value_" + count)

            ' Save changes to the file.
            config.Save()

            ' Read the new appSettings.
            ReadAppSettings(config)
        Catch err As Exception
            Console.WriteLine(err.ToString())
        End Try

    End Sub 'UpdateConfiguration


    ' Update the configuration file using the credentials
    ' of the passed user,  then call the routine that reads 
    ' the configuration settings.
    ' Note that the system issues an error if the user
    ' does not have administrative privileges on the server.
    Public Overloads Shared Sub UpdateConfiguration(ByVal _
        machineName As String, ByVal userName As String, ByVal _
        password As String)
        Try
            Console.WriteLine("MachineName:  [{0}]", machineName)
            Console.WriteLine("UserName:  [{0}]", userName)
            Console.WriteLine("Password:  [{0}]", password)

            ' Get the configuration.
            Dim config As Configuration = _
                WebConfigurationManager.OpenWebConfiguration("/", _
                "Default Web Site", Nothing, machineName, _
                userName, password)


            ' Add a new key/value pair to appSettings
            Dim count As String = _
                config.AppSettings.Settings.Count.ToString()
            config.AppSettings.Settings.Add("key_" + _
                count, "value_" + count)
            ' Save to the file,
            config.Save()

            ' Read the new appSettings.
            ReadAppSettings(config)

        Catch err As Exception
            Console.WriteLine(err.ToString())
        End Try

    End Sub 'UpdateConfiguration


    ' Read the appSettings on the remote server.
    Public Shared Sub ReadAppSettings(ByVal config As Configuration) 
        Try
            Console.WriteLine("--- Printing appSettings at [{0}] ---", _
                config.FilePath)
            Console.WriteLine("Count: [{0}]", _
                config.AppSettings.Settings.Count)
            Dim key As String
            For Each key In  config.AppSettings.Settings.AllKeys
                Console.WriteLine("  [{0}] = [{1}]", _
                    key, config.AppSettings.Settings(key).Value)
            Next key
            Console.WriteLine()

        Catch err As Exception
            Console.WriteLine(err.ToString())
        End Try

    End Sub 'ReadAppSettings
End Class 'RemoteConfiguration

using System;
using System.Configuration;
using System.Web.Configuration;
using System.Collections.Specialized;

namespace Samples.AspNet
{
    // This example dDemonstrates how to access and modify remote 
   // configuration files
    public class RemoteConfiguration
    {

        // The application entry point.
        public static void Main(string[] args)
        {
            // This string  contains the name of 
            // the remote server.
            string machineName = string.Empty;

            // Get the user's input.
            if (args.Length > 0)
            {
                // Get the name of the remote server.
                // The machine name must be in the format
                // accepted by the operating system.
                machineName = args[0];

                // Get the user name and password.
                if (args.Length > 1)     
                {                
                    string userName = args[1];
                    string password = string.Empty;
                    if (args.Length > 2)
                        password = args[2];

                    // Update the site configuration.
                    UpdateConfiguration(machineName, userName, 
                        password);
                }
                else
                { 
                    // Update the site configuration.
                    UpdateConfiguration(machineName);
                }
            }
            else
            {
                Console.WriteLine("Enter a valid server name.");
            }
        }

        // Update the configuration file using the credentials
        // of the user running this application then
        // call the routine that reads the configuration 
        // settings.
        // Note that the system issues an error if the user
        // does not have administrative privileges on the server.
        public static void UpdateConfiguration(string machineName)
        {
            try
            {
                Console.WriteLine("MachineName:  [{0}]", machineName);
                Console.WriteLine("UserDomainName:  [{0}]", 
                    Environment.UserDomainName);
                Console.WriteLine("UserName:  [{0}]", 
                    Environment.UserName);

                // Get the configuration.
                Configuration config = 
                    WebConfigurationManager.OpenWebConfiguration(
                    "/", "Default Web Site", null, machineName);

                // Add a new key/value pair to appSettings.
                string count = 
                    config.AppSettings.Settings.Count.ToString();
                config.AppSettings.Settings.Add("key_" + count, "value_" + count);
                // Save to the file,
                config.Save();

                // Read the new appSettings.
                ReadAppSettings(config);
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }
        }

         // Update the configuration file using the credentials
         // of the passed user. Tthen,
     // call the routine that reads the configuration settings.
        // Note that the system issues an error if the user
        // does not have administrative privileges on the server.
        public static void UpdateConfiguration(string machineName, 
            string userName, string password)
        {
            try
            {
                Console.WriteLine("MachineName:  [{0}]", machineName);
                Console.WriteLine("UserName:  [{0}]", userName);
                Console.WriteLine("Password:  [{0}]", password);

                // Get the configuration.
                Configuration config = 
                    WebConfigurationManager.OpenWebConfiguration(
                    "/", "Default Web Site", null, 
                    machineName, userName, password);


                // Add a new key/value pair to appSettings
                string count =
                    config.AppSettings.Settings.Count.ToString();
                config.AppSettings.Settings.Add("key_" + count, "value_" + count);

             // Save changes to the file.
                config.Save();

                // Read the new appSettings.
                ReadAppSettings(config);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        // Read the appSettings on the remote server.
        public static void ReadAppSettings(
            Configuration config)
        {
            try
            {
                Console.WriteLine("--- Printing appSettings at [{0}] ---", 
                    config.FilePath);
                Console.WriteLine("Count: [{0}]", 
                    config.AppSettings.Settings.Count);
                foreach (string key in config.AppSettings.Settings.AllKeys)
                {
                    Console.WriteLine("  [{0}] = [{1}]", 
                        key, config.AppSettings.Settings[key].Value);
                }
                Console.WriteLine();

            }           
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }
        }
    }

}

前一個程式碼範例會讀取並修改為伺服器之「預設的網站」所設定的 appSettings 項目值。然後在主控台上顯示該項目值。

程式碼會使用下列方法:

  • OpenWebConfiguration 可將 Web 應用程式的組態檔當做 Configuration 物件開啟。請注意,在遠端伺服器上的隱含使用者必須有系統管理權限。

  • OpenWebConfiguration 可將 Web 應用程式的組態檔當做 Configuration 物件開啟。請注意,參數清單中所指定的使用者在遠端伺服器上必須有系統管理權限。

  • AppSettings 可存取預設網站的相關區段。

  • GetSection 可存取預設網站的識別區段。

編譯程式碼

若要編譯主控台應用程式,您必須使用下列命令。

vbc /out:RemoteConfiguration.exe /t:exe RemoteConfiguration.vb
/r:System.Web.dll /r:System.Configuration.dll
csc /out: RemoteConfiguration.exe /t:exe RemoteConfiguration.cs
/r:System.Web.dll /r:System.Configuration.dll

安全性

若要存取遠端伺服器上的組態檔,您的應用程式必須在該遠端伺服器上具有系統管理員的權限。

注意事項:

這項需求比存取本機組態檔所要具備的需求更嚴格。若要存取本機檔案,應用程式只需要讀取/寫入權限,以及對 IIS Metabase 的讀取權限以解析路徑。

請參閱

概念

編輯 ASP.NET 遠端組態檔

使用組態類別

ASP.NET 組態概觀

參考

System.Configuration

System.Web.Configuration

ASP.NET IIS 註冊工具 (Aspnet_regiis.exe)

其他資源

設定應用程式