다음을 통해 공유


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

업데이트: 2007년 11월

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

처리기는 System.Configuration.IConfigurationSectionHandler 인터페이스 또는 System.Configuration.ConfigurationSection 클래스를 구현하는 .NET Framework 클래스여야 합니다.

참고:

이 항목에서는 .NET Framework 버전 2.0에서는 더 이상 사용되지 않는 System.Configuration.IConfigurationSectionHandler 인터페이스를 사용합니다. System.Configuration.ConfigurationSection 클래스를 사용하는 예제를 보려면 방법: ConfigurationSection을 사용하여 사용자 지정 구성 섹션 만들기를 참조하십시오. 아래 코드 예제를 사용하는 경우 .NET Framework 버전 1.0 또는 1.1을 사용하여 빌드하십시오.

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

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

  1. 다음 코드에 표시된 것처럼 System.Configuration.IConfigurationSectionHandler 인터페이스를 구현하는 공용 클래스를 만듭니다.

    Imports System
    Imports System.Collections
    Imports System.Text
    Imports System.Configuration
    Imports System.Xml
    
    Namespace MyConfigSectionHandler
      Public Class MyHandler
        Implements IConfigurationSectionHandler
    
        Public Function Create( _
        ByVal parent As Object, ByVal configContext As Object, ByVal section As System.Xml.XmlNode) _
        As Object Implements System.Configuration.IConfigurationSectionHandler.Create
    
          Throw New System.Exception("The method is not implemented.")
    
        End Function
      End Class
    End Namespace
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Configuration;
    using System.Xml;
    
    namespace MyConfigSectionHandler
    {
      public class MyHandler : IConfigurationSectionHandler
      {
        #region IConfigurationSectionHandler Members
    
        object IConfigurationSectionHandler.Create(
            object parent, object configContext, XmlNode section)
        {
          throw new Exception("The method is not implemented.");
        }
    
        #endregion
      }
    }
    
  2. 원하는 구성 작업을 수행하는 자체 코드를 추가합니다.

    예를 들어, throw new Exception("The method is not implemented."); 줄을 section 매개 변수의 Attributes 속성에서 특성 이름 및 값을 가져오는 코드로 바꾼 후 사용자 지정 구성 개체를 반환할 수 있습니다. 다음 예제에서는 Hashtable을 구성 개체로 사용합니다.

    Imports System
    Imports System.Collections
    Imports System.Text
    Imports System.Configuration
    Imports System.Xml
    
    Namespace MyConfigSectionHandler
    
      Public Class MyHandler
        Implements IConfigurationSectionHandler
    
        Public Function Create( _
        ByVal parent As Object, ByVal configContext As Object, ByVal section As System.Xml.XmlNode) _
        As Object Implements System.Configuration.IConfigurationSectionHandler.Create
    
          ' Creates the configuration object that this method will return.
          ' This can be a custom configuration class.
          ' In this example, we use a System.Collections.Hashtable.
          Dim myConfigObject As New Hashtable
    
          ' Gets any attributes for this section element.
          Dim myAttribs As New Hashtable
          For Each attrib As XmlAttribute In section.Attributes
            If XmlNodeType.Attribute = attrib.NodeType Then
              myAttribs.Add(attrib.Name, attrib.Value)
            End If
          Next
    
          ' Puts the section name and attributes as the first config object item.
          myConfigObject.Add(section.Name, myAttribs)
    
          ' Gets the child element names and attributes.
          For Each child As XmlNode In section.ChildNodes
            If XmlNodeType.Element = child.NodeType Then
              Dim myChildAttribs As New Hashtable
    
              For Each childAttrib As XmlAttribute In child.Attributes
                If XmlNodeType.Attribute = childAttrib.NodeType Then
                  myChildAttribs.Add(childAttrib.Name, childAttrib.Value)
                End If
              Next
              myConfigObject.Add(child.Name, myChildAttribs)
            End If
          Next
    
          Return (myConfigObject)
    
        End Function
    
      End Class
    
    End Namespace
    
    using System;
    using System.Collections;
    using System.Text;
    using System.Configuration;
    using System.Xml;
    
    namespace MyConfigSectionHandler
    {
      public class MyHandler : IConfigurationSectionHandler
      {
        #region IConfigurationSectionHandler Members
    
        object IConfigurationSectionHandler.Create(
          object parent, object configContext, XmlNode section)
        {
          // Creates the configuration object that this method will return.
          // This can be a custom configuration class.
          // In this example, we use a System.Collections.Hashtable.
          Hashtable myConfigObject = new Hashtable();
    
          // Gets any attributes for this section element.
          Hashtable myAttribs = new Hashtable();
          foreach (XmlAttribute attrib in section.Attributes)
          {
            if (XmlNodeType.Attribute == attrib.NodeType)
              myAttribs.Add(attrib.Name, attrib.Value);
          }
    
          // Puts the section name and attributes as the first config object item.
          myConfigObject.Add(section.Name, myAttribs);
    
          // Gets the child element names and attributes.
          foreach (XmlNode child in section.ChildNodes)
          {
            if (XmlNodeType.Element == child.NodeType)
            {
              Hashtable myChildAttribs = new Hashtable();
    
              foreach (XmlAttribute childAttrib in child.Attributes)
              {
                if (XmlNodeType.Attribute == childAttrib.NodeType)
                  myChildAttribs.Add(childAttrib.Name, childAttrib.Value);
              }
              myConfigObject.Add(child.Name, myChildAttribs);
            }
          }
    
          return (myConfigObject);
        }
        #endregion
      }
    }
    

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

  1. 다음 코드에 표시된 것처럼 Web.config 파일의 configSections 요소 내에 sectionGroupsection 요소를 추가합니다.

    참고:

    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>
    

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

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

    이전 예제와 함께 작동하는 다음 ASPX 페이지 예제에서는 단추를 클릭할 때 사용자 지정 구성 섹션의 특성 및 자식 요소를 열거합니다.

    사용자 지정 섹션 처리기가 Hashtable을 구성 개체로 사용하므로 GetSection 메서드는 Hashtable을 반환합니다.

    다음 코드는 .aspx 페이지에 포함됩니다. 다음 코드 예제에서는 숨김 파일에 포함되는 단추 클릭 이벤트의 코드를 보여 줍니다.

    다음 코드 예제에는 .NET Framework 버전 1.0 또는 1.1이 필요합니다.

    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="BugTest.WebForm1" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 
    
    <html>
      <head>
        <title>WebForm1</title>
        <meta name="GENERATOR" 
              Content="Microsoft Visual Studio .NET 2003">
        <meta name="CODE_LANGUAGE" Content="C#">
        <meta name=vs_defaultClientScript content="JavaScript">
        <meta name=vs_targetSchema 
              content="https://schemas.microsoft.com/intellisense/ie5">
      </head>
      <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" >
        <h1>Enumerate MyCustomSection</h1>
        <asp:Label ID="Label1"  
            Text="" />
        <br />
        <asp:Button ID="Button1"  
            Text="Get Custom Config Info" 
            OnClick="Button1_Click" />
        </form>
      </body>
    </html>
    
    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
      <HEAD>
        <title>WebForm1</title>
        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 2003">
        <meta name="CODE_LANGUAGE" Content="VB">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="https://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" >
          <h1>Enumerate MyCustomSection</h1>
          <asp:Label ID="Label1"  Text="" />
          <br>
          <asp:Button ID="Button1"  Text="Get Custom Config Info" OnClick="Button1_Click" />
        </form>
      </body>
    </HTML>
    

    단추 클릭 이벤트에 대한 다음 코드는 앞서 나온 .aspx 페이지에 속하는 코드 숨김 파일에 포함됩니다. 코드 숨김 파일 이름의 확장명으로는 @Page 선언의 language 특성에 따라 .aspx.cs 또는 .aspx.vb가 사용됩니다.

    [C#]

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Configuration;
    using System.Text;
    
    namespace BugTest
    {
        /// <summary>
        /// Summary description for WebForm1.
        /// </summary>
        public class WebForm1 : System.Web.UI.Page
        {
            protected System.Web.UI.WebControls.Label Label1;
            protected System.Web.UI.WebControls.Button Button1;
    
            private void Page_Load(object sender, System.EventArgs e)
            {
                // Put user code to initialize the page here
            }
    
            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                //
                // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                //
                InitializeComponent();
                base.OnInit(e);
            }
    
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                this.Button1.Click += new System.EventHandler(this.Button1_Click);
                this.Load += new System.EventHandler(this.Page_Load);
    
            }
            #endregion
    
            protected void Button1_Click(object sender, System.EventArgs e)
            {
                Hashtable config = 
    (Hashtable)System.Configuration.ConfigurationSettings.GetConfig("myCustomGroup/myCustomSection");
    
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("Config object item count = {0}<br/><br/>", config.Count);
                foreach (DictionaryEntry deKey in config)
                {
                    sb.AppendFormat("<h2>Attributes in the {0} Element:</h2>", 
                        deKey.Key.ToString());
                    Hashtable attribs = (Hashtable)deKey.Value;
                    foreach (DictionaryEntry deAttrib in attribs)
                    {
                        sb.AppendFormat("{0} = {1}<br/>", 
                            deAttrib.Key.ToString(), deAttrib.Value.ToString());
                    }
                }
                Label1.Text = sb.ToString();
                Label1.Visible = true;
    
            }
        }
    }
    
    Imports System.Text
    
    Public Class WebForm1
      Inherits System.Web.UI.Page
    
    #Region " Web Form Designer Generated Code "
    
      'This call is required by the Web Form Designer.
      <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    
      End Sub
      Protected WithEvents Label1 As System.Web.UI.WebControls.Label
      Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    
      'NOTE: The following placeholder declaration is required by 
      ' the Web Form Designer.
      'Do not delete or move it.
      Private designerPlaceholderDeclaration As System.Object
    
      Private Sub Page_Init(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
      End Sub
    
    #End Region
    
      Private Sub Page_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
      End Sub
    
      Protected Sub Button1_Click(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles Button1.Click
        Dim config As Hashtable = _
    System.Configuration.ConfigurationSettings.GetConfig( _
    "myCustomGroup/myCustomSection")
    
        Dim sb As New StringBuilder
        sb.AppendFormat("Config object item count = {0}<br/><br/>", _
    config.Count)
    
        For Each deKey As DictionaryEntry In config
          sb.AppendFormat("<h2>Attributes in the {0} Element:</h2>", _
    deKey.Key.ToString())
          Dim attribs As Hashtable = deKey.Value
          For Each deAttrib As DictionaryEntry In attribs
            sb.AppendFormat("{0} = {1}<br/>", deAttrib.Key.ToString(), _
    deAttrib.Value.ToString())
          Next
          Label1.Text = sb.ToString()
          Label1.Visible = True
        Next
    
      End Sub
    End Class
    

참고 항목

작업

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

개념

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

기타 리소스

ASP.NET 웹 사이트 관리

ASP.NET 웹 사이트 관리

응용 프로그램 구성