Share via


방법: 원격으로 ASP.NET 구성 파일 액세스 및 수정

업데이트: 2007년 11월

System.ConfigurationSystem.Web.Configuration 형식을 사용하여 응용 프로그램에서 원격 서버에 있는 구성 파일에 액세스할 수 있습니다. 특히 원격 서버에 있는 Microsoft 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 - 웹 응용 프로그램의 구성 파일을 Configuration 개체로 엽니다. 이때 사용자에게 원격 서버에 대한 관리 권한이 있어야 합니다.

  • OpenWebConfiguration - 웹 응용 프로그램의 구성 파일을 Configuration 개체로 엽니다. 매개 변수 목록에 지정된 사용자에게 원격 서버에 대한 관리 권한이 있어야 합니다.

  • AppSettings - 기본 사이트 관련 섹션에 액세스합니다.

  • GetSection - 기본 사이트 ID 섹션에 액세스합니다.

코드 컴파일

콘솔 응용 프로그램을 컴파일하려면 다음 명령을 사용해야 합니다.

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 메타베이스를 읽을 수만 있으면 해당 파일에 액세스할 수 있습니다.

참고 항목

개념

ASP.NET 원격 구성 파일 편집

구성 클래스 사용

ASP.NET 구성 개요

참조

System.Configuration

System.Web.Configuration

ASP.NET IIS 등록 도구(Aspnet_regiis.exe)

기타 리소스

응용 프로그램 구성