Previous Section  < Day Day Up >  Next Section

17.2. ASP.NET and Configuration Files

One of the advantages of working with ASP.NET, as a developer or administrator, is the ease of configuring and customizing the settings. The use of XML-based configuration files replaces the previous ASP approach that required shutting down and restarting server software to change a setting or replace DLLs. Now, changes that affect the underlying behavior of a Web page can be made dynamically. The beauty of this approach is that changes can be made using a simple text editor梐lthough an XML editor is preferable梐nd that ASP.NET automatically detects and applies these changes when they occur.

Configuration information is stored in a required machine.config file and optional web.config files. The format of these files is the same; the difference is their scope.

As shown in Figure 17-3, configuration files can be placed in a hierarchy on the Web server. Each file lower down in the hierarchy overrides the settings (with a few exceptions) of files above it. The machine.config file is at the top of the hierarchy, and its settings apply to all applications running on the machine. Web.config files placed in application directories and subdirectories apply their settings to a specific application or pages in an application.

Figure 17-3. Hierarchy of configuration files

Core Note

As an alternative to a text editor, ASP.NET includes a configuration editor with the IIS management console. It is accessed from the Properties menu of a virtual directory.

A Look Inside web.config

The web.config file is an XML-formatted text file comprising numerous sections and subsections. Listing 17-3 offers a sampling of sections you're likely to find most useful: <configSections>, <appSettings>, <location>, <system.web>, and <connectionStrings>. After summarizing key features of these predefined sections, we'll look at how to create a custom configuration section.

Listing 17-3. Sample web.config File (continued)


<!-- (1) Define custom configurations                -->


      <section name="RewriterConfig" 

         type="RewriteSectionHandler, URLRewriter" />



      <!-- Contents of custom configuration section -->


<!-- (2) Place application data in here              -->


      <add key="mainFont" value="arial" />

      <add key="fontSize" value="2" />  


<!-- (3) Define system.web settings for a directory  -->

   <location path="calculators\bmi">  


         <trace enabled="true"

         pageOutput="true" />



<!-- (4) Main ASP.NET Application settings            -->




         timeout=20  />



<!-- (5) Connection string for database               --> 


      <!-- connection string description  -->



<appSettings> Configuration Section

This area is used by developers to hold constant data values required by an application. These values typically include preference settings that define the appearance of a Web page. This entry illustrates how font settings are added using an <add> element and a key-value pair of attributes:

<add key="mainFont" value="arial" />

Values are retrieved from the appSettings section using the static AppSettings property of the ConfigurationSettings class:

myFont = ConfigurationSettings.AppSettings["mainFont"];

<location> Configuration Section

As mentioned previously, web.config files can be placed hierarchically within a directory structure, with files at lower levels overriding the settings of files in parent directories. This approach permits you to tailor the actions of ASP.NET down to the application and page level. However, this flexibility brings with it the potential problem of keeping track of the settings in multiple configuration files. As an alternative, ASP.NET provides a way to configure the settings for multiple directories in a single web.config file by using <location> elements. The <location> section operates as a configuration file within a configuration file. The element has a path attribute that takes the value of a virtual directory name. The settings within the contained <system.web> block apply to the virtual directory.

As an example, suppose that during application development we want to view the trace information as we test our applications. Because we don't want this voluminous output in the final product, we can set up a virtual "test" directory and enable tracing for that directory only.

<location path="test">


      <trace enabled="true" pageOutput="true" />



This has the same effect as placing a web.config file with this trace setting in the physical directory associated with the "test" virtual directory.

<system.web> Configuration Section

This is the area in web.config where an administrator can configure just about any aspect of the ASP.NET environment. It can be used to set session time-out length, user authentication and authorization rules, the type of session state management used, and the default culture used for processing requests. Table 17-3 summarizes the more important elements in this section.

Table 17-3. Selected system.web Elements




Sets default language and debug option.


Defines custom errors and error pages.


Enables or disables the trace feature for an application.


Sets default Web page attributes.


Defines response/request encoding and culture-specific setting for Web pages.


Used to configure process setting for an IIS Web server.


Specifies authentication mode for a client: Windows, Forms, Passport, None.


Allows or denies access to resources.


Defines how the Membership class manages user credentials and authentication.


Specifies whether client impersonation is used on a Web page request.


Configures the session state features of ASP.NET.

Of particular interest are the authentication, authorization, and membership elements that are discussed in Section 17.3, "ASP.NET Application Security." Other useful sections are summarized here.

The <compilation> Section

Use the debug attribute to indicate whether debugging symbols will be included in the compiled code. The defaultLanguage attribute sets the default language used in a Web page's script blocks. Multiple languages can be selected by using a semicolon to separate them.

<compilation  debug="true"  defaultLanguage="C#"  />

The <customErrors> Section

The primary use of this section is to redirect errors to custom Web pages. Here is an entry that establishes a default error page, and a page to handle the HTTP 404 status code that arises when a resource cannot be found:

<customErrors defaultRedirect = "defaultError.aspx" mode="On" >

   <error statusCode="404" redirect="Error404.aspx" />


The mode attribute takes the value On, Off, or RemoteOnly. The latter value, which is also the default, specifies that the default page is called only if the request comes from a machine other than the Web server. This permits local developers to see details of the actual error, whereas clients see only the custom page. Off should be used when a developer is testing pages on a remote machine. Note that multiple <error> elements can be included in the section.

The <trace> Section

The <trace> element is used to enable application-level trace logging. This is in contrast to the trace attribute of the <%@Page> directive that provides only page-level tracing. Here is an example that illustrates the use of the <trace> element and its associated attributes:








Aside from the enabled attribute that turns tracing on or off, the most interesting attributes are pageOutput and localOnly.

  • pageOutput specifies whether the trace log is appended to the Web page for display on the client's browser. If set to false, the output can be viewed in the TRace.axd page of the application's root. Here is an example:

    Application URL:


    Trace log:


  • The requestLimit attribute sets the maximum number of trace logs maintained.

  • localOnly indicates whether tracing is enabled for localhost users only or all users. The default is true.

The <sessionState> Section

One of the more powerful features of ASP.NET is the ability to maintain state information for a session; and the <sessionState> element plays a definitive role in selecting how it is implemented. By setting its mode attribute to one of four values, the software architect can specify where the session state information is stored.

  • off disables the use of session state management.

  • Inproc enables in-process state management (aspnet_state.exe).

  • StateServer state is stored by a surrogate process running on a selected server.

  • SqlServer state is maintained in a temporary SQL Server table.

These options are described in detail in Section 17.4. Our interest in this section is to understand the elements and attributes that define how ASP.NET manages session state. To illustrate, here are the default settings for the <sessionState> element:









The timeout attribute specifies the number of minutes the session can be idle before it is abandoned. The cookieless attribute indicates whether the identification of the client session is maintained using a cookie or by mangling the URL (placing encoded session information in the URL line). The other two attributes are dependent upon the mode setting: stateConnectString specifies the IP address of the machine running the Session State Server process, and sqlConnectionString contains the connection string value used to access SQL Server if it is used to maintain state information.

The <connectionStrings> Section

Prior to .NET version 2.0, developers usually resorted to storing connection strings as a key-value pair in the <appSettings> section. ASP.NET 2.0 now provides a predefined <connectionStrings> section for this purpose. As shown in this example, the section takes three attributes: name, connectionString, and providerName.


  <add name="movies"


      "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=/movies.mdb;"



The connection string is retrieved using the ConfigurationSettings class, which retrieves the string associated with a specified name attribute. Note that multiple strings may be defined.

string cs= 


Adding a Custom Configuration Section

The web.config file can be a convenient place to stash information needed by an application. We saw earlier how simple name/value pairs can be stored in the <appSettings> section. Suppose, however, your application requires data represented by a more complex XML structure. The solution is to add a custom configuration section to web.config. However, it is not as simple as choosing a configuration name and inserting appropriately formatted code into the configuration file. When you try to access a Web application that uses the configuration file, you'll receive an Unrecognized Configuration Section error.

It turns out that each section in web.config has a special handler that parses the section and makes its content available to an application. This handler is a class that implements the System.Configuration.IConfigurationSectionHandler interface and is declared in the <configSections> section of the web.config file.

Core Note

You can view the section handlers for the standard predefined sections, such as <appSections> in the machine.config file.

To demonstrate how section handlers work, let's create one for the <RewriterConfig> section shown in the code that follows. The first thing to note is the <configSections> element that contains a definition of the new section. Its type attribute specifies the handler (class) that parses the <RewriterConfig> section. The data section represents URLs that have been changed and need to be replaced with a new URL.


   <sectionGroup name="RewriterConfig">

      <section name="RewriterRules"

         type="ConfigRewriter.RulesHandler,RulesConfigHandler" />



<!--   Custom Configuration Section for URL Rewriting -->













After the XML data structure is determined, the next step in developing a section handler is to create a class that is populated with the contents of the section and contains members that make the data available to an application. In this example, data is defined by any number of <Rule> elements. Consequently, the class must provide some sort of collection to return multiple values. We'll use a Hashtable for the purpose. The GetNewPath method accepts a string value that it uses as a key to retrieve and return its associated value from the hash table.

// File: SectionRules.cs

using System.Collections;

namespace ConfigRewriter


   // Class to contain content of configuration section

   public class RulesData


      private Hashtable paths;

      // Constructor accepts hash table as parameter

      public RulesData (Hashtable pathCollection){

         paths = pathCollection; 


      // Use old path as key and return hash table value

      public string GetNewPath(string OldUrl) 


         return ((string)paths[OldUrl]);




The final step, shown in Listing 17-4, is to create the section handler code. Its primary function is to implement the Create method. This method is passed an XMLNode parameter that corresponds to the <RewriterRules> node in our section. It is used to parse its child nodes and fill the hash table with its contents. An instance of the RulesData class is instantiated by passing the hash table to its constructor. This object is then available to a Web application.

Listing 17-4. Configuration Section Handler

//File: RedirectConfigHandler.cs

using System.Xml;

using System.Configuration;

using System.Collections;

namespace ConfigRewriter


   public class RulesHandler: IConfigurationSectionHandler


     public object Create(object parent, object input, 

                          XmlNode section)


        Hashtable paths = new Hashtable();

        string oldUrl="";

        XmlElement root = (XmlElement) section;

        foreach (XmlNode node in root.ChildNodes){

           foreach(XmlNode child in node.ChildNodes) 


              if(child.Name=="OldPath") oldUrl= child.InnerText;



                 paths[oldUrl]= child.InnerText;




        RulesData urlRules = new RulesData(paths);

        return urlRules;      




After the section has been constructed, accessing its content is trivial: use the ConfigurationSettings.GetConfig method to return an instance of the section object, and use its properties to retrieve values.

// Retrieve object returned by section handler

// and use it to access content of section

RulesData r;

r = ConfigurationSettings.GetConfig(


      as RulesData;


// Pass old path to method and receive redirected path

string newURL = r.GetNewPath("/ideas/bmi.aspx");

    Previous Section  < Day Day Up >  Next Section