Share via


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

업데이트: 2007년 11월

자신만의 XML 구성 요소를 사용하여 ASP.NET 구성 설정 표준 집합을 확장할 수 있습니다. 이렇게 하려면 자신만의 구성 섹션 처리기를 만들어야 합니다.

처리기는 System.Configuration.ConfigurationSection 클래스를 구현하는 .NET Framework 클래스여야 합니다.

참고:

.NET Framework 버전 1.0 및 1.1에서는 구성 섹션 처리기에서 System.Configuration.IConfigurationSectionHandler 인터페이스를 구현해야 했습니다. 이 인터페이스는 지금은 사용되지 않지만 방법: IConfigurationSectionHandler를 사용하여 사용자 지정 구성 섹션 만들기에 코드 예제가 있습니다.

섹션 처리기는 Web.config 파일의 특정 부분 내에 있는 XML 구성 요소에서 정의된 설정을 해석 및 처리하며 구성 설정에 따라 적절한 구성 개체를 반환합니다. 처리기 클래스가 반환하는 구성 개체는 임의의 데이터 구조가 될 수 있으며, 기본 구성 클래스나 구성 형식에 제한을 받지 않습니다. ASP.NET에서는 이러한 구성 개체를 사용하여 사용자 지정 구성 요소를 읽거나 이 요소에 씁니다.

사용자 지정 구성 섹션 처리기를 만들려면

  1. 다음 코드 예제에 표시된 것처럼 System.Configuration.ConfigurationSection 클래스를 상속하는 공용 클래스를 만듭니다.

    Imports System
    Imports System.Collections
    Imports System.Text
    Imports System.Configuration
    Imports System.Xml
    
    Namespace MyConfigSectionHandler
    
        Public Class MyHandler
            Inherits ConfigurationSection
    
            Public Sub New()
            End Sub
    
            ' Add declarations for child elements and attributes like this:
            '<ConfigurationProperty("<propertyName>", <named parameters>)> _
            'Public Property MyAttrib1() As <type>
            '    Get
            '        Return CStr(Me("<propertyName>"))
            '    End Get
            '    Set(ByVal value As <type>)
            '        Me("<propertyName>") = value
            '    End Set
            'End Property
    
        End Class
    End Namespace
    
    using System;
    using System.Collections;
    using System.Text;
    using System.Configuration;
    using System.Xml;
    
    namespace MyConfigSectionHandler
    {
        public class MyHandler : ConfigurationSection
        {
            public MyHandler()
            {
            }
    
            // Add declarations for child elements and attributes like this:
            // [ConfigurationProperty("<propertyName>", <named parameters>)]
            // public <type> <PropertyName>
            // {
            //     get { return (<type>)this["<propertyName>"]; }
            //     set { this["<propertyName>"] = value; }
            // }
        }
    }
    
  2. 원하는 구성 작업을 수행하는 자체 코드를 추가합니다.

    예를 들어, 주석으로 처리된 코드를 사용자 지정 구역에서 값을 가져오는 다음 코드로 바꿀 수 있습니다.

    Imports System
    Imports System.Collections
    Imports System.Text
    Imports System.Configuration
    Imports System.Xml
    
    Namespace MyConfigSectionHandler
    
        Public Class MyHandler
            Inherits ConfigurationSection
    
            Public Sub New()
            End Sub
    
            Public Sub New(ByVal attribVal As String)
                MyAttrib1 = attribVal
            End Sub
    
            <ConfigurationProperty("myAttrib1", DefaultValue:="Clowns", IsRequired:=True)> _
            <StringValidator(InvalidCharacters:="~!@#$%^&*()[]{}/;'\|\\", MinLength:=1, MaxLength:=60)> _
            Public Property MyAttrib1() As String
                Get
                    Return CStr(Me("myAttrib1"))
                End Get
                Set(ByVal value As String)
                    Me("myAttrib1") = value
                End Set
            End Property
    
            <ConfigurationProperty("myChildSection")> _
            Public Property MyChildSection() As MyChildConfigElement
                Get
                    Return CType(Me("myChildSection"), MyChildConfigElement)
                End Get
                Set(ByVal value As MyChildConfigElement)
                    Me("myChildSection") = CType(value, MyChildConfigElement)
                End Set
            End Property
        End Class
    
        Public Class MyChildConfigElement
            Inherits ConfigurationElement
    
            Public Sub New()
            End Sub
    
            Public Sub New( _
            ByVal a1 As String, ByVal a2 As String)
                MyChildAttribute1 = a1
                MyChildAttribute2 = a2
            End Sub
    
            <ConfigurationProperty("myChildAttrib1", DefaultValue:="Zippy", IsRequired:=True)> _
            <StringValidator(InvalidCharacters:="~!@#$%^&*()[]{}/;'\|\\", MinLength:=1, MaxLength:=60)> _
            Public Property MyChildAttribute1() As String
                Get
                    Return CStr(Me("myChildAttrib1"))
                End Get
                Set(ByVal value As String)
                    Me("myChildAttrib1") = value
                End Set
            End Property
    
            <ConfigurationProperty("myChildAttrib2", DefaultValue:="Michael Zawondy", IsRequired:=True)> _
            <StringValidator(InvalidCharacters:="~!@#$%^&*()[]{}/;'\|\\", MinLength:=1, MaxLength:=60)> _
            Public Property MyChildAttribute2() As String
                Get
                    Return CStr(Me("myChildAttrib2"))
                End Get
                Set(ByVal value As String)
                    Me("myChildAttrib2") = value
                End Set
            End Property
    
        End Class
    End Namespace
    
    using System;
    using System.Collections;
    using System.Text;
    using System.Configuration;
    using System.Xml;
    
    namespace MyConfigSectionHandler
    {
        public class MyHandler : ConfigurationSection
        {
            public MyHandler()
            {
            }
    
            public MyHandler(String attribVal)
            {
                MyAttrib1 = attribVal;
            }
    
            [ConfigurationProperty("myAttrib1", DefaultValue = "Clowns", IsRequired = true)]
            [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
            public String MyAttrib1
            {
                get
                { return (String)this["myAttrib1"]; }
                set
                { this["myAttrib1"] = value; }
            }
    
            [ConfigurationProperty("myChildSection")]
            public MyChildConfigElement MyChildSection
            {
                get
                { return (MyChildConfigElement)this["myChildSection"]; }
                set
                { this["myChildSection"] = value; }
            }
        }
    
        public class MyChildConfigElement : ConfigurationElement
        {
            public MyChildConfigElement()
            {
            }
    
            public MyChildConfigElement(String a1, String a2)
            {
                MyChildAttribute1 = a1;
                MyChildAttribute2 = a2;
            }
    
            [ConfigurationProperty("myChildAttrib1", DefaultValue = "Zippy", IsRequired = true)]
            [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
            public String MyChildAttribute1
            {
                get
                { return (String)this["myChildAttrib1"]; }
                set
                { this["myChildAttrib1"] = value; }
            }
    
            [ConfigurationProperty("myChildAttrib2", DefaultValue = "Michael Zawondy", IsRequired = true)]
            [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
            public String MyChildAttribute2
            {
                get
                { return (String)this["myChildAttrib2"]; }
                set
                { this["myChildAttrib2"] = value; }
            }
        }
    }
    

    이 예제에서는 선언적 모델을 사용합니다. 프로그래밍 방식 모델을 사용하여 System.Configuration.ConfigurationSection 클래스를 구현할 수도 있습니다. 예제는 System.Configuration.ConfigurationSection 클래스 개요 항목과 사용자 지정 섹션 처리기를 만드는 데 사용되는 클래스를 참조하십시오.

    비교를 위해 이 예제는 방법: IConfigurationSectionHandler를 사용하여 사용자 지정 구성 섹션 만들기의 코드와 비슷합니다. 하지만 섹션 처리기를 좀 더 세밀하게 조정할 수 있도록 System.Configuration.ConfigurationSection 클래스에서 상속됩니다. 예를 들어, 다음 절차의 구성 파일에서는 앞의 코드에서 ConfigurationProperty를 선언하고 ConfigurationElement에서 파생된 클래스로 정의하는 myChildSection라는 자식 요소를 사용할 수 있습니다. 또한 ConfigurationElementCollection 클래스에서 컬렉션 기능의 캡슐화를 사용하면 구성 파일에서 요소를 사용, 추가, 제거 및 지울 수 있는 컬렉션 요소를 쉽게 만들 수 있습니다. 자세한 내용과 예제를 보려면 ConfigurationElementCollection을 참조하십시오.

ASP.NET 구성 파일에 사용자 지정 섹션 처리기를 추가하려면

  1. 다음 코드 예제에 표시된 것처럼 Web.config 파일의 configSections 요소 내에 sectionGroup 요소 및 section 요소를 추가합니다. 이 선언에서 사용자 지정 섹션 처리기를 섹션 이름과 연결합니다.

    참고:

    section 요소를 sectionGroup에 중첩시키는 것은 선택적이지만 구성 데이터의 적절한 구성을 위해 권장됩니다.

    사용자 지정 구성 요소를 추가한 구성 파일과는 다른 구성 파일에 섹션 처리기 선언을 추가할 수 있습니다. 단, 섹션 처리기가 선언된 구성 파일이 구성 파일 계층에서 더 높은 수준에 있어야 합니다. 자세한 내용은 ASP.NET 구성 파일 계층 구조 및 상속을 참조하십시오.

    section 요소의 type 특성은 어셈블리의 매니페스트와 일치해야 하며 그렇지 않으면 구성 오류가 발생합니다. 어셈블리 파일 자체는 해당 어셈블리를 정의하는 Web.config 파일과 동일한 ASP.NET 응용 프로그램 디렉터리에 있어야 합니다.

    <configuration>
    
    <!-- Configuration section-handler declaration area. -->
      <configSections>
        <sectionGroup name="myCustomGroup">
          <section 
            name="myCustomSection" 
            type="MyConfigSectionHandler.MyHandler, MyCustomConfigurationHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" 
            allowLocation="true" 
            allowDefinition="Everywhere"
          />
        </sectionGroup>
          <!-- Other <section> and <sectionGroup> elements. -->
      </configSections>
    
      <!-- Configuration section settings area. -->
    
    </configuration>
    
  2. Web.config 파일의 구성 섹션 설정 영역에 사용자 지정 구성 요소를 추가합니다.

    <configuration>
    
    <!-- Configuration section-handler declaration area. -->
    
      <!-- Configuration section settings area. -->
      <myCustomGroup>
        <myCustomSection myAttrib1="Clowns">
          <myChildSection 
              myChildAttrib1="Zippy" 
              myChildAttrib2="Michael Zawondy "/>
        </myCustomSection>
      </myCustomGroup>
    
      <!-- Other configuration settings, like <system.web> -->
    
    </configuration>
    

프로그래밍 방식으로 사용자 지정 구성 데이터에 액세스하려면

  • 사용자 지정 구성 개체 인스턴스를 가져온 후 GetSection 메서드나 GetSection 메서드를 사용하여 채웁니다.

    다음 ASPX 페이지 예제는 이전 예제를 사용하여 사용자 지정 구성 섹션의 특성 및 자식 요소를 열거합니다.

    <%@ Page Language="C#" %>
    
    <script >
        protected void Button1_Click(object sender, EventArgs e)
        {
            MyConfigSectionHandler.MyHandler config =
                (MyConfigSectionHandler.MyHandler)System.Configuration.ConfigurationManager.GetSection(
                "myCustomGroup/myCustomSection");
    
            StringBuilder sb = new StringBuilder();
    
            sb.Append("<h2>Attributes in the myCustomSection Element:</h2>");
            sb.AppendFormat("myAttrib1 = {0}<br/>", config.MyAttrib1.ToString());
            sb.Append("<h2>Attributes in the myChildSection Element:</h2>");
            sb.AppendFormat("myChildAttrib1 = {0}<br/>", config.MyChildSection.MyChildAttribute1.ToString());
            sb.AppendFormat("myChildAttrib2 = {0}<br/>", config.MyChildSection.MyChildAttribute2.ToString());
    
            Label1.Text = sb.ToString();
            Label1.Visible = true;
        }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head >
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
    
        <h1>Enumerate MyCustomSection</h1>
        <asp:Label ID="Label1"  
            Text="" />
        <br />
        <asp:Button ID="Button1"  
            Text="Get Custom Config Info" 
            OnClick="Button1_Click" />
    
        </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="VB" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script >
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim config As New MyConfigSectionHandler.MyHandler
            config = _
                System.Configuration.ConfigurationManager.GetSection("myCustomGroup/myCustomSection")
            Dim sb As New StringBuilder
            sb.Append("<h2>Attributes in the myCustomSection Element:</h2>")
            sb.AppendFormat("myAttrib1 = {0}<br/>", config.MyAttrib1.ToString())
            sb.Append("<h2>Attributes in the myChildSection Element:</h2>")
            sb.AppendFormat("myChildAttrib1 = {0}<br/>", config.MyChildSection.MyChildAttribute1.ToString())
            sb.AppendFormat("myChildAttrib2 = {0}<br/>", config.MyChildSection.MyChildAttribute2.ToString())
    
            Label1.Text = sb.ToString()
            Label1.Visible = True
    
        End Sub
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head >
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
    
        <h1>Enumerate MyCustomSection</h1>
        <asp:Label ID="Label1"  
            Text=""/>
        <br />
        <asp:Button ID="Button1"  
            Text="Get Custom Config Info" 
            OnClick="Button1_Click" />
    
        </div>
        </form>
    </body>
    </html>
    

참고 항목

개념

ASP.NET 구성 파일 구조(섹션 및 섹션 처리기)

ASP.NET 구성 개요

기타 리소스

ASP.NET 웹 사이트 관리

응용 프로그램 구성