Freigeben über


Gewusst wie: Öffnen und Ändern von ASP.NET-Konfigurationsdateien über Remotezugriff

Aktualisiert: November 2007

Mithilfe des System.Configuration-Typs und des System.Web.Configuration-Typs kann eine Anwendung auf die Konfigurationsdateien auf einem Remoteserver zugreifen. Insbesondere können Sie die Datei Machine.config oder Web.config in jeder Microsoft IIS-Anwendung oder ihren untergeordneten Verzeichnissen auf einem Remoteserver öffnen und ändern. In diesem Thema werden mehrere Aspekte behandelt:

  • Es wird veranschaulicht, wie Sie festlegen, dass der Remoteserver den Zugriff eines Clientcomputers auf die Serverkonfigurationsdateien zulässt.

  • Es wird eine Konsolenanwendung bereitgestellt, die auf dem Clientcomputer ausgeführt wird und die Serverkonfigurationsdateien lesen oder ändern kann.

  • Es werden die Sicherheitsaspekte erörtert, die beachtet werden müssen.

Der Clientcomputer muss für den Zugriff auf die Konfigurationsdateien auf einem Remoteserver mit dem Server kommunizieren können. Für die Kommunikation muss auf dem Server eine Remotekonfigurationskomponente installiert sein.

Der Clientcomputer greift dann auf die Serverkonfigurationsdateien zu, indem er über die Remotekonfigurationskomponente die ASP.NET-Konfigurations-API aufruft. Weitere Informationen hierzu finden Sie unter Bearbeiten von ASP.NET-Remotekonfigurationsdateien.

Hinweis:

Wenn die angeforderte Konfigurationsdatei nicht vorhanden ist, gibt das auf dem Server ausgeführte .NET Framework eine Konfigurationsdatei zurück, die ausschließlich aus geerbten Einstellungen besteht, die für den angegebenen Pfad gültig sind. Wenn die Anwendung eine Aktualisierung anfordert, wird eine neue Datei erstellt. Beim Ausführen der Konsolenanwendung müssen Sie einen gültigen Servernamen eingeben. Dies ist erforderlich, weil ASP.NET diesen Namen direkt an das Betriebssystem übergibt. Sie müssen außerdem einen vollqualifizierten Benutzernamen mit dem Domänennamen als Präfix eingeben.

So richten Sie den Remoteserver ein

  1. Installieren Sie unter Verwendung des ASP.NET IIS-Registrierungstools (Aspnet_regiis.exe) mit dem Befehl config+ die Remotekonfigurationskomponente auf dem Server, wie im folgenden Code gezeigt.

    Aspnet_regiis config+
    
  2. Stellen Sie programmgesteuert oder manuell sicher, dass die Datei Web.config der "Standardwebsite" des IIS-Servers Werte enthält, die den folgenden Werten entsprechen:

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

So aktualisieren Sie die Remotekonfigurationsdateien mithilfe einer Konsolenanwendung

  • Führen Sie die im folgenden Codebeispiel bereitgestellte Konsolenanwendung aus, um die Datei Web.config der Standardwebsite auf dem Remoteserver zu aktualisieren. In diesem Beispiel wird davon ausgegangen, dass der Benutzer, der die Clientanwendung ausführt, über Administratorrechte für den Remoteserver verfügt. Sie können einen dieser beiden Befehle verwenden.

    >remoteconfiguration machineName
    >remoteconfiguration machineName domainName\userName password
    

Beispiel

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());
            }
        }
    }

}

Im vorherigen Codebeispiel werden die Werte des für die Standardwebsite des Servers konfigurierten appSettings-Elements gelesen und geändert. Anschließend werden die Werte in der Konsole angezeigt.

Im Code werden die folgenden Methoden verwendet:

  • OpenWebConfiguration, um die Konfigurationsdatei der Webanwendung als Configuration-Objekt zu öffnen. Beachten Sie, dass der Benutzer über Administratorrechte auf dem Remoteserver verfügen muss.

  • OpenWebConfiguration, um die Konfigurationsdatei der Webanwendung als Configuration-Objekt zu öffnen. Beachten Sie, dass der in der Parameterliste angegebene Benutzer über Administratorrechte auf dem Remoteserver verfügen muss.

  • AppSettings, um auf den Abschnitt für die Standardsite zuzugreifen.

  • GetSection, um auf den Abschnitt für die Standardsiteidentität zuzugreifen.

Kompilieren des Codes

Zum Kompilieren der Konsolenanwendung müssen Sie den folgenden Befehl verwenden.

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

Sicherheit

Die Anwendung muss für den Zugriff auf eine Konfigurationsdatei auf einem Remoteserver über Administratorrechte für diesen Remoteserver verfügen.

Hinweis:

Diese Anforderung ist strenger als die Anforderung für den Zugriff auf lokale Konfigurationsdateien. Für den Zugriff auf lokale Dateien benötigt die Anwendung nur Lese-/Schreibberechtigungen und Lesezugriff auf die IIS-Metabasis, um den Pfad aufzulösen.

Siehe auch

Konzepte

Bearbeiten von ASP.NET-Remotekonfigurationsdateien

Verwenden der Konfigurationsklassen

Übersicht über die ASP.NET-Konfiguration

Referenz

System.Configuration

System.Web.Configuration

ASP.NET IIS-Registrierungstool (Aspnet_regiis.exe)

Weitere Ressourcen

Konfigurieren von .NET Framework-Anwendungen