Share via


Procedura: creare sezioni di configurazione personalizzate tramite IConfigurationSectionHandler

Aggiornamento: novembre 2007

È possibile estendere il set standard delle impostazioni di configurazione ASP.NET con altri elementi di configurazione XML. Per eseguire questa operazione, è necessario creare un gestore della sezione di configurazione personalizzato.

Il gestore deve essere una classe .NET Framework che implementa l'interfaccia System.Configuration.IConfigurationSectionHandler o la classe System.Configuration.ConfigurationSection.

Nota:

In questo argomento viene utilizzata l'interfaccia System.Configuration.IConfigurationSectionHandler, obsoleta in .NET Framework versione 2.0. Per un esempio che utilizza la classe System.Configuration.ConfigurationSection, vedere Procedura: creare sezioni di configurazione personalizzate tramite ConfigurationSection. Se si utilizzano gli esempi di codice riportati di seguito, generarli con .NET Framework versione 1.0 o 1.1.

Il gestore della sezione interpreta ed elabora le impostazioni definite negli elementi di configurazione XML all'interno di una sezione specifica di un file Web.config e restituisce l'oggetto di configurazione appropriato in base alle impostazioni di configurazione. L'oggetto di configurazione restituito dalla classe del gestore può corrispondere a qualsiasi struttura di dati e non è limitato a nessuna classe di configurazione o formato di configurazione di base. ASP.NET utilizza l'oggetto di configurazione per leggere e scrivere nell'elemento di configurazione personalizzato.

Per creare un gestore di sezione di configurazione personalizzato

  1. Creare una classe pubblica che implementa l'interfaccia System.Configuration.IConfigurationSectionHandler, come illustrato nel seguente esempio di codice.

    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. Aggiungere il codice personalizzato per eseguire le operazioni di configurazione desiderate.

    È possibile, ad esempio, sostituire la riga throw new Exception("The method is not implemented."); con il codice che ottiene i valori e i nomi degli attributi dalla proprietà Attributes del parametro section e restituire un oggetto di configurazione personalizzato. Nell'esempio seguente viene utilizzata una classe Hashtable come oggetto di configurazione.

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

Per aggiungere un gestore di sezione personalizzato a un file di configurazione ASP.NET

  1. Aggiungere un elemento sectionGroup e section al file Web.config all'interno dell'elemento configSections, come illustrato nel seguente codice.

    Nota:

    La nidificazione di un elemento section in un elemento sectionGroup è facoltativa, sebbene sia consigliabile per organizzare i dati di configurazione.

    È possibile aggiungere la dichiarazione del gestore di sezione in un file di configurazione diverso da quello in cui sono stati aggiunti gli elementi di configurazione personalizzati, purché il file di configurazione in cui viene dichiarato il gestore di sezione si trovi a un livello superiore nella gerarchia di file di configurazione. Per ulteriori informazioni, vedere Gerarchia ed ereditarietà dei file di configurazione di ASP.NET.

    Se l'attributo type dell'elemento section non corrisponde al manifesto dell'assembly, si verificherà un errore di configurazione. Lo stesso file assembly deve trovarsi nella stessa directory dell'applicazione ASP.NET del file Web.config che lo definisce.

    <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. Aggiungere gli elementi di configurazione personalizzati nell'area delle impostazioni della sezione di configurazione del file 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>
    

Per accedere a livello di codice ai dati di configurazione personalizzati

  • Ottenere un'istanza dell'oggetto di configurazione personalizzato e utilizzare il metodo ConfigurationManager.GetSection o il metodo WebConfigurationManager.GetSection per compilarlo.

    Nel seguente esempio di pagina ASPX vengono utilizzati gli esempi precedenti per enumerare gli attributi e gli elementi figlio della sezione di configurazione personalizzata quando si fa clic su un pulsante.

    Poiché il gestore di sezione personalizzato utilizza una classe Hashtable come oggetto di configurazione, il metodo GetSection restituisce una Hashtable.

    Il codice riportato di seguito viene inserito nella pagina ASPX. Il codice relativo all'evento Click del pulsante, che viene inserito nel file code-behind, è contenuto nell'esempio di codice successivo.

    Gli esempi di codice riportati di seguito richiedono .NET Framework versione 1.0 o 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>
    

    Il codice riportato di seguito, relativo all'evento Click del pulsante, viene inserito nel file code-behind che appartiene alla precedente pagina ASPX. Il file code-behind utilizza l'estensione ASPX.CS o ASPX.VB, a seconda dell'attributo language della dichiarazione @Page.

    [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
    

Vedere anche

Attività

Procedura: creare sezioni di configurazione personalizzate tramite ConfigurationSection

Concetti

Struttura dei file di configurazione ASP.NET (Sezioni e gestori della sezione)

Altre risorse

Amministrazione di siti Web ASP.NET

Amministrazione di siti Web ASP.NET

Configurazione di applicazioni