ASP.NET Configuration Logical Model

Understanding the organizational principles behind configuration can help you to better use this important system feature. The configuration settings can control an application's behavior at run time, so that you do not necessarily need to rebuild it. This topic describes the logical organization of the ASP.NET configuration sections, the related programming model, and their relationships.

Note

For information about the configuration files' hierarchy or their interdependence, see the documentation areas listed in the See Also section.

Configuration File Logical Organization

A configuration file contains all or some of the following logical areas. If a particular area is not defined, the file in question inherits that area from the parent file in the configuration file hierarchy. The logical areas are:

  • Configuration handlers. This area, delimited by the opening and closing configSections tags, contains the definitions for the handlers associated with the sections. A handler is a class that implements the IConfigurationSectionHandler interface and interprets the settings and related values of the associated configuration section. It is important to note that each section in a configuration file must have a handler. If you include a section without an associated handler, ASP.NET throws an exception.

  • Configuration sections. The configuration sections are the building blocks of a configuration file and contain the actual settings. Each section name should match the name declared in its related section handler. A section can contain multiple settings and other child sections.

  • Configuration section attributes. These are the section attributes defined by names and related values.

  • Configuration groups. You can contain configuration sections in section groups. These groups are used for organizational purposes, and can be defined more than once in a single configuration file if each group contains different sections. One common group is system.web. It contains the definitions for all the configuration sections that apply to ASP.NET. Notice that the name of the group is the same as the .NET Framework namespace System.Web.

A special role is played by the location Element (ASP.NET Settings Schema). The location element specifies the resource that child configuration settings apply to and is also used to lock configuration settings, preventing the settings from being overridden by child configuration files. Refer to Locking Configuration Settings.

Configuration Section Relationships

To effectively use the configuration system, you must understand how the various configuration sections are connected and how they work together. There are two types of relationships between configuration sections:

  • Organizational connection. The simplest connection is the one implied by the configuration file organization. This connection manifests itself as the nesting of configuration sections. Consider for example the compilation section and its subsections, the healthMonitoring section and its subsections, and so on.

  • System connection. A more subtle connection is the one between different non-nested sections. An example is the relationship that exists between authentication and authorization; another is the relationship between securityPolicy and trust; yet another is between authentication and membership.

Configuration Programming Model

The ASP.NET configuration programming model is mainly provided by the types defined in the System.Configuration, System.Web.Configuration, and System.Configuration.Provider namespaces.

These types give you a flexible API that not only allows access to the underlying configuration but also helps you to extend it by allowing the creation of custom sections and handlers.

The following example shows the API flexibility and simplicity by quickly creating a custom section.

Imports System
Imports System.Configuration
Imports System.Web
Imports System.Web.Configuration
Imports System.Web.Security
Imports System.Reflection


Namespace Samples.AspNet



    ' Define a custom configuration.PublicClass CustomConfiguration




        PublicSubNew()

        EndSub 'New

        ' Define a custom section.PublicClass CustomSection
            Inherits ConfigurationSection

            PrivateConst configString AsString = "aString"PrivateConst configInteger AsString = "anInteger"PrivateConst configTimeout AsString = "aTimeout"



            <ConfigurationProperty(CustomSection.configString, DefaultValue:="default")> _
            PublicProperty aString() AsStringGetReturnCStr(Me(CustomSection.configString))
                EndGetSet(ByVal value AsString)
                    Me(CustomSection.configString) = value
                EndSetEndProperty




            <ConfigurationProperty(CustomSection.configInteger, DefaultValue:=1)> _
            PublicProperty anInteger() AsIntegerGetReturn Fix(Me(CustomSection.configInteger))
                EndGetSet(ByVal value AsInteger)
                    Me(CustomSection.configInteger) = value
                EndSetEndProperty




            <ConfigurationProperty(CustomSection.configTimeout)> _
            PublicProperty aTimeout() As TimeSpan


                GetReturnCType(Me(CustomSection.configTimeout), TimeSpan)
                EndGetSet(ByVal value As TimeSpan)
                    Me(CustomSection.configTimeout) = value
                EndSetEndPropertyEndClass 'CustomSection



        ' Create a custom section and save it in the        ' application configuration file.PublicSub CreateCustomSection()

            Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration("/ConfigSite")

            Dim section As CustomSection = config.Sections("CustomSection")

            If section IsNothingThen
                ' Create section and add it to the configuration.
                section = New CustomSection()
                config.Sections.Add("CustomSection", section)
            EndIf
            ' Assign configuration settings.
            section.aTimeout = TimeSpan.FromSeconds(DateTime.Now.Second)

            section.anInteger = 1500

            section.aString = "Hello World"

            ' Save the changes.
            config.Save()

        EndSub 'CreateCustomSection


        ' Get the custom section stored in         ' the configuration file.PublicFunction GetCustomSection() AsStringDim config As Configuration = WebConfigurationManager.OpenWebConfiguration("/ConfigSite")


            Dim section As CustomSection = config.Sections("CustomSection")

            Dim currentSection AsString = String.Empty

            IfNot (section IsNothing) Then
                currentSection = HttpContext.Current.Server.HtmlEncode(section.SectionInformation.GetRawXml())

            Else
                currentSection = "CustomSection does not exist"EndIfReturn currentSection

        EndFunction 'GetCustomSection
    EndClass 'CustomConfiguration

EndNamespace
using System;
using System.Configuration;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Reflection;

namespace Samples.AspNet
{
    // Define a custom configuration.publicclass CustomConfiguration
    {



        public CustomConfiguration()
        {

        }


        // Define a custom section.publicclass CustomSection : ConfigurationSection
        {

            conststring configString = "aString";

            conststring configInteger = "anInteger";

            conststring configTimeout = "aTimeout";


            [ConfigurationProperty(CustomSection.configString,

                DefaultValue = "default")]

            publicstring aString
            {

                get { return (string)base[CustomSection.configString]; }

                set { base[CustomSection.configString] = value; }

            }



            [ConfigurationProperty(CustomSection.configInteger,

                DefaultValue = 1)]

            publicint anInteger
            {

                get { return (int)base[CustomSection.configInteger]; }

                set { base[CustomSection.configInteger] = value; }

            }



            [ConfigurationProperty(CustomSection.configTimeout)]

            public TimeSpan aTimeout
            {

                get { return (TimeSpan)base[CustomSection.configTimeout]; }

                set { base[CustomSection.configTimeout] = value; }

            }

        }


        // Create a custom section and save it in the// application configuration file.publicvoid CreateCustomSection()
        {

            Configuration config =
                WebConfigurationManager.OpenWebConfiguration("/ConfigSite");

            CustomSection section =
                config.Sections["CustomSection"] as CustomSection;

            if (section == null)
            {

                // Create section and add it to the configuration.
                section = new CustomSection();
                config.Sections.Add("CustomSection", section);

            }

            // Assign configuration settings.
            section.aTimeout = 
                TimeSpan.FromSeconds(DateTime.Now.Second);

            section.anInteger = 1500;

            section.aString = "Hello World";


            // Save the changes.

            config.Save();

        }

        // Get the custom section stored in // the configuration file.publicstring GetCustomSection()
        {


            Configuration config =
                WebConfigurationManager.OpenWebConfiguration("/ConfigSite");


            CustomSection section =
                config.Sections["CustomSection"] as CustomSection;


            string currentSection = string.Empty;

            if (section != null)
            {
                currentSection = HttpContext.Current.Server.HtmlEncode(
                    section.SectionInformation.GetRawXml());     

            }
            else
                currentSection = "CustomSection does not exist";

            return currentSection;
        }
    }

}

You can add the preceding source code to the App_Code directory of a Web application and run it by executing the following example.

[Visual Basic]

Imports System
Imports System.Configuration
Imports System.Web
Imports Samples.AspNet

Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        ' Create a custom section.
        Dim cc As New CustomConfiguration()
        cc.CreateCustomSection()

        ' Display the section settings.
        CustomId.Text = cc.GetCustomSection()

    End Sub 'Page_Load
End Class

[C#]

using System;
using System.Configuration;
using System.Web;
using Samples.AspNet;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a custom section.
        CustomConfiguration cc = 
            new CustomConfiguration();
        cc.CreateCustomSection();

        // Display the section settings.
        CustomId.Text = cc.GetCustomSection();
    }
}

After you run the preceding example, the Web.config file associated with the application contains the following custom section definitions.

<configuration>

    <configSections>
      <section name="CustomSection" 
        type="Samples.AspNet.CustomConfiguration+CustomSection, App_Code" />
    </configSections>

    <CustomSection aString="Hello World" anInteger="1500" aTimeout="00:00:34" />

</configuration>

See Also

Concepts

Using the Configuration Classes

ASP.NET Configuration Overview

Locking Configuration Settings

Reference

configSections Element (General Settings Schema)

location Element (ASP.NET Settings Schema)

Other Resources

Configuring Applications