Share via


Cómo: Crear secciones de configuración personalizadas mediante ConfigurationSection

Actualización: noviembre 2007

Si lo desea, puede extender el conjunto estándar de opciones de configuración de ASP.NET con sus propios elementos XML de configuración. Para ello, debe crear su propio controlador de sección de configuración.

El controlador debe ser una clase de .NET Framework que implemente la clase System.Configuration.ConfigurationSection.

Nota:

En las versiones 1.0 y 1.1 de .NET Framework, un controlador de sección de configuración debía implementar la interfaz System.Configuration.IConfigurationSectionHandler, que ahora ya no se utiliza. Sin embargo, hay un ejemplo de código en Cómo: Crear secciones de configuración personalizadas mediante IConfigurationSectionHandler.

El controlador de sección interpreta y procesa las opciones definidas en los elementos de configuración XML dentro de una parte específica de un archivo Web.config y devuelve el objeto de configuración correspondiente basado en las opciones de configuración. El objeto de configuración devuelto por la clase de controlador puede ser cualquier estructura de datos; no está limitado por ninguna clase de configuración básica o ningún formato de configuración. ASP.NET utiliza el objeto de configuración para leer y escribir en su elemento de configuración personalizado.

Para crear un controlador de sección de configuración personalizado

  1. Cree una clase pública que herede la clase System.Configuration.ConfigurationSection, como se ilustra en el ejemplo de código siguiente.

    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. Agregue su propio código para realizar el trabajo de configuración que desee.

    Por ejemplo, puede reemplazar el código marcado como comentario con el código siguiente, que obtiene los valores de la sección personalizada.

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

    En este ejemplo se utiliza el modelo declarativo. La clase System.Configuration.ConfigurationSection también se puede implementar utilizando el modelo de programación. Dispone de un ejemplo en el tema de información general de la clase System.Configuration.ConfigurationSection y Clases utilizadas para crear identificadores de sección personalizados.

    Para poder comparar, este ejemplo es similar al código de Cómo: Crear secciones de configuración personalizadas mediante IConfigurationSectionHandler. Sin embargo, el hecho de heredar de la clase System.Configuration.ConfigurationSection permite controlar con mayor precisión el controlador de sección. Por ejemplo, el archivo de configuración del procedimiento siguiente incluye un elemento secundario denominado myChildSection, para el cual el código anterior declara un objeto ConfigurationProperty y lo define como clase derivada de ConfigurationElement. Asimismo, la encapsulación de funcionalidad de colección de la clase ConfigurationElementCollection permite crear fácilmente elementos de colección que pueden emplear elementos add, remove y clear en un archivo de configuración. Para obtener más información y ejemplos, vea ConfigurationElementCollection.

Para agregar un controlador de sección personalizado a un archivo de configuración de ASP.NET

  1. Agregue un elemento sectionGroup y un elemento section al archivo Web.config, dentro del elemento configSections, como se ilustra en el ejemplo de código siguiente. Es esta declaración la que asocia el controlador de sección personalizado al nombre de sección.

    Nota:

    La anidación de elementos section en elementos sectionGroup es opcional, aunque se recomienda, para organizar mejor los datos de configuración.

    Puede agregar la declaración del controlador de sección en un archivo de configuración diferente del archivo en el que agrega los elementos de configuración personalizados, siempre y cuando el archivo de configuración donde se declare el controlador de sección ocupe una posición superior en la jerarquía de archivos de configuración. Para obtener más información, vea Jerarquía de archivos y herencia de la configuración de ASP.NET.

    El atributo type del elemento section debe coincidir con el manifiesto del ensamblado; de lo contrario, se producirá un error de configuración. El propio archivo de ensamblado debe estar en el mismo directorio de aplicación ASP.NET que el archivo Web.config que lo define.

    <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. Agregue sus elementos de configuración personalizados en el área de la sección de configuración de su archivo 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>
    

Para tener acceso mediante programación a sus datos de configuración personalizados

  • Obtenga una instancia del objeto de configuración personalizado y utilice el método GetSection o el método GetSection para rellenarla.

    El ejemplo siguiente de una página ASPX funciona con los ejemplos anteriores para enumerar los atributos y elementos secundarios de la sección de configuración personalizada.

    <%@ 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>
    

Vea también

Conceptos

Estructura de archivos de configuración de ASP.NET (secciones y controladores de sección)

Información general sobre la configuración de ASP.NET

Otros recursos

Administrar sitios web ASP.NET

Configurar aplicaciones