외부 파일에서 구성 변경 예제

업데이트: 2007년 11월

외부 구성 파일을 사용하여 응용 프로그램 구성 설정을 확장하고, 응용 프로그램 다시 시작 기능을 활성화하거나 비활성화하는 방법으로 이러한 설정이 변경되는 경우 상태 정보가 보존되는지 여부를 제어할 수 있습니다. 이 기능은 각기 다른 구성 파일 섹션에 적용되는 restartOnExternalChanges 특성을 통해 제어됩니다.

샘플 웹 응용 프로그램 파일

다음 섹션에는 configSource 특성이 외부 구성 파일을 가리키고 초기에 restartOnExternalChanges 특성이 true로 설정되는 사용자 지정 섹션이 있는 샘플 웹 응용 프로그램을 빌드하는 코드가 포함되어 있습니다.

이 웹 응용 프로그램을 실행하면 외부 구성 파일이 변경된 경우 전역 다시 게시 카운터에 발생하는 결과가 표시됩니다. 여기 나와 있는 코드 예제에서는 restartOnExternalChanges가 각각 true, 기본값 및 false로 설정된 경우의 결과를 보여 줍니다.

Global.asax

샘플 웹 응용 프로그램에는 이 Global.asax 페이지가 포함되어야 합니다. 다음 코드 예제에서는 전역 다시 게시 카운터가 포함된 페이지를 정의합니다. 이 카운터는 응용 프로그램의 Default.aspx 페이지를 새로 고쳐 생성되는 다시 게시 요청을 추적합니다. 이 페이지에 대한 정의는 이 항목의 뒷부분에 나와 있습니다.

' Code that runs on application startup.
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) 
    
    ' This counter is set to 0 the first time 
    ' the application starts and, thereafter, every 
    ' time it restarts.
    Dim postBackCount As Integer = 0
    
    Dim appState As HttpApplicationState = Application.Contents
    appState.Add("postBackKey", postBackCount)

End Sub 'Application_Start
// Code that runs on application startup.
void Application_Start(object sender, EventArgs e) 
{
       
        // This counter is set to 0 the first time 
        // the application starts and, thereafter, every 
        // time it restarts.
        int postBackCount = 0;
        
        HttpApplicationState appState = Application.Contents;
        appState.Add("postBackKey", postBackCount);
        
}

Default.aspx

Default.aspx 페이지는 Web.config 파일에 사용자 지정 섹션을 만드는 코드를 포함하며 External.config 파일에 요소를 추가하고 다시 게시 카운터 값을 표시합니다. 다시 게시 카운터의 현재 값을 표시하려면 이 페이지에 Label 컨트롤이 포함되어야 합니다. 다음 코드 예제에서는 이 컨트롤을 정의하는 방법 중 한 가지를 보여 줍니다.

<asp:Label ID="ResultId"  style="font-weight:bold; color:Red;"/>

다음 코드 예제에서는 Default.aspx 페이지를 정의합니다.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 
        Dim extConfig As ExternalConfiguration = Nothing
        
        If Not IsPostBack Then
            ' Create an instance of the custom section.
            extConfig = New ExternalConfiguration()
        End If
                
        Dim postBackCount As Integer = _
        Fix(HttpContext.Current.Application("postBackKey"))
        'Display current counter value.
        ResultId.Text = postBackCount.ToString()
        
        HttpContext.Current.Application("postBackKey") = _
        Fix(HttpContext.Current.Application("postBackKey")) + 1
        
        extConfig.UpdateAppSettngs()
End Sub 'Page_Load
protected void Page_Load(object sender, EventArgs e)
{
        ExternalConfiguration extConfig = null;
        
        if (!IsPostBack)
        {
            // Create an instance of the cusom section.
            extConfig =
                new ExternalConfiguration();
        }

        int postBackCount =
           (int) HttpContext.Current.Application["postBackKey"];
        ResultId.Text = postBackCount.ToString();

        HttpContext.Current.Application["postBackKey"] =
            (int)HttpContext.Current.Application["postBackKey"] + 1;
 
        extConfig.UpdateAppSettngs();
}

Web.config

Web.config 파일은 다음 코드 예제와 같이 MyAppSettings 사용자 지정 섹션을 정의합니다. 이 예제에서는 표준 형식을 사용하여 이 섹션을 처리하지만 고유한 형식을 직접 만들 수도 있습니다. 자세한 내용은 ConfigurationElementConfigurationSection을 참조하십시오.

<section 
    name="MyAppSettings" 
    type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
    restartOnExternalChanges="true" 
    requirePermission="false" />

External.config

External.config 파일에는 MyAppSettings 사용자 지정 섹션의 세부 사항이 포함됩니다. 응용 프로그램을 처음으로 실행하기 전에 응용 프로그램의 루트 디렉터리에 이 파일을 직접 만들어야 합니다. 자세한 내용은 section 요소에서 상속된 일반 특성에서 configSource 특성을 참조하십시오. 이 예제의 경우 코드에 다음과 같은 빈 섹션이 포함되어 있어야 합니다.

<MyAppSettings></ MyAppSettings>.

ExternalConfiguration.dll

ExternalConfiguration.dll 파일에는 MyAppSettings 사용자 지정 섹션을 업데이트하는 코드가 포함됩니다. 소스 코드를 응용 프로그램의 App_Code 디렉터리에 배치할 수 있습니다. ASP.NET에서는 응용 프로그램이 요청될 때 이 예제를 컴파일합니다. 샘플 공급자를 라이브러리로 컴파일한 다음 웹 응용 프로그램의 Bin 디렉터리에 배치할 수도 있습니다. 다음 코드 예제에서는 명령줄에서 샘플을 컴파일하는 방법을 보여 줍니다.

vbc /out: ExternalConfiguration.dll /t:library ExternalConfiguration.vb /r:System.Web.dll /r:System.Configuration.dll
csc /out: ExternalConfiguration.dll /t:library ExternalConfiguration.cs /r:System.Web.dll /r:System.Configuration.dll

다음 코드 예제에서는 ExternalConfiguration .dll 파일을 빌드합니다.

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Web.Configuration

Namespace Samples.AspNet


    Public Class ExternalConfiguration


        ' Instantiate the ExternalConfiguration type.
        Public Sub New()
            ' Access the root Web.config file.
            Dim config As System.Configuration.Configuration = _
            WebConfigurationManager.OpenWebConfiguration("/configTarget")

            ' Get the custom MyAppSettings section.
            Dim appSettings As AppSettingsSection = _
            CType(config.GetSection("MyAppSettings"), AppSettingsSection)

            ' Perform the first update.
            UpdateAppSettings()

        End Sub 'New



        ' Update the custom MyAppSettings section.
        ' Note , if the section restartOnExternalChanges attribute 
        ' is set to true, every update of the external 
        ' configuration file will cause the application 
        ' to restart.
        Public Sub UpdateAppSettings()

            Dim config As System.Configuration.Configuration = _
            WebConfigurationManager.OpenWebConfiguration("/configTarget")

            Dim appSettings As AppSettingsSection = _
            CType(config.GetSection("MyAppSettings"), AppSettingsSection)

            Dim count As Integer = appSettings.Settings.Count

            appSettings.Settings.Add("key_" + count.ToString(), _
            "value_" + count.ToString())

            config.Save()

        End Sub 'UpdateAppSettngs

    End Class 'ExternalConfiguration 

End Namespace
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web.Configuration;

namespace Samples.AspNet
{


    public class ExternalConfiguration
    {

        // Instantiate the ExternalConfiguration type.
        public ExternalConfiguration()
        {
            // Access the root Web.config file.
            System.Configuration.Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                              "/configTarget");

            // Get the custom MyAppSettings section.
            AppSettingsSection appSettings =
                (AppSettingsSection)config.GetSection("MyAppSettings");

            // Perform the first update.
            UpdateAppSettings();
        }


        // Update the custom MyAppSettings section.
        // Note , if the section restartOnExternalChanges attribute 
        // is set to true, every update of the external 
        // configuration file will cause the application 
        // to restart.
        public void UpdateAppSettings()
        {

            System.Configuration.Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                              "/configTarget");

            AppSettingsSection appSettings =
                (AppSettingsSection)config.GetSection("MyAppSettings");

            int count = appSettings.Settings.Count;

            appSettings.Settings.Add(
                "key_" + count.ToString(), 
                "value_" + count.ToString());

            config.Save();
        }

    }
}

샘플 웹 응용 프로그램 사용

이 응용 프로그램을 처음 실행하면 External.config 파일에 요소가 추가됩니다.

Default.aspx 페이지를 새로 고칠 때마다 다시 게시 카운터가 0으로 재설정됩니다. 이는 MyAppSettings 섹션의 restartOnExternalChanges 특성이 기본적으로 true로 설정되어 있기 때문입니다.

Web.config 파일에서 restartOnExternalChanges 특성을 false로 설정하면 External.config 파일의 내용을 변경하더라도 페이지를 새로 고칠 때 다시 게시 카운터가 계속 증가하는 것을 알 수 있습니다. 이는 응용 프로그램 도메인 다시 시작 기능을 비활성화했기 때문입니다.

참고 항목

작업

방법: ConfigurationSection을 사용하여 사용자 지정 구성 섹션 만들기

개념

구성 설정에 대한 변경 내용 관리

ASP.NET 구성 보안

참조

ConfigurationElement

ConfigurationSection

section 요소에서 상속된 일반 특성

location

appSettings 요소(일반 설정 스키마)

trace 요소(ASP.NET 설정 스키마)

HttpApplicationState