Chapter 15. Configuring Your Application

In this chapter, you will learn how to configure your ASP.NET applications by taking advantage of the Machine.Config and Web.Config files. You can use these files to modify a variety of configuration settings, including security, compilation, and trace settings.

In this chapter, you will learn

  • How to modify the different sections of the Machine.Config and Web.Config files

  • How to store custom configuration information in the Machine.Config and Web.Config files

  • How to perform advanced configuration tasks, such as locking configuration sections

Overview of the Machine.Config and Web.Config Files

One of the goals of the .NET Framework is to eliminate the need to use the Windows registry to store application configuration settings. This is good news because dependence on the Windows registry results in a number of problems:

  • Storing configuration information in the Windows registry makes it difficult to move an application from one server to another. In particular, it makes it difficult to move an application from a development server to a production server because every registry setting must be moved from one server to the other.

  • The Windows registry can become corrupted, causing your application to fail.

  • You must use special utilities to edit the Windows registry, which makes it difficult to perform quick modifications.

The .NET Framework replaces the Windows registry with the Machine.Config and Web.Config files. These files are plain text files in XML format. You can edit them with any text editor, including Notepad.

The Machine.Config file contains configuration settings that apply to every .NET application on a server. It's the master configuration file. You can find this file at WINNTMicrosoft.NETFrameworkVersionCONFIG.

Typically, you do not modify the Machine.Config file. Instead, you override configuration settings in the Machine.Config file within a lower-level Web.Config file. The Web.Config file doesn't contain any additional sections that are not included in the Machine.Config file.

You can place a Web.Config file in a number of different locations. The location of the Web.Config file determines the scope of its configuration settings:

  • wwwroot—If you place a Web.Config file in the root directory of a Web site, it applies to all Web applications contained within the Web site.

  • virtual root—If you place a Web.Config file in the root directory of a virtual directory, it applies to a particular ASP.NET application.

  • directory—If you place a Web.Config file in a particular directory, it applies to all files in that directory and all files located in directories below that directory.

  • file—You can apply settings in a Web.Config file to a single file (see the “Applying Configuration Settings to a Particular File” section later in this chapter).

The Machine.Config and Web.Config files work hierarchically. As you'll see in a moment, the Machine.Config file is huge. However, if you want to override a configuration setting in a Web.Config file, you don't need to copy the whole Machine.Config into the Web.Config file. You can copy only those settings that you want to override.

Configuration Sections

In this section, we'll examine each of the configuration sections in the Machine.Config file. This section will make more sense if you open the Machine.Config file in Notepad so you can take a look at it as you read about the different configuration sections. The Machine.Config file is located at WINNTMicrosoft.NETFrameworkVersionCONFIG.

The first thing you should notice about the Machine.Config file is that it is an XML file. This has some inconvenient implications. In particular, it means that the Machine.Config file is case sensitive. Adding a <System.Web> tag is different from adding a <system.web> tag.

Note

In general, tag names in the Machine.Config file follow a naming convention called camel casing. When names are camel cased, the first letter of the first word in a name is lowercase, and the first letters of any remaining words in a name are uppercase. For example, requestEncoding instead of RequestEncoding.

On the other hand, the values of attributes follow a convention called Pascal casing. The first letter of all words in the value of an attribute is uppercase. For example, SortByCategory instead of sortByCategory.

On the positive side, the fact that the Machine.Config file is an XML file makes it easy to edit. You can make any modifications to the Machine.Config or Web.Config directly within Notepad. As soon as you save the modified file, any changes that you make will immediately take effect.

Tip

You can buy user-friendly editors for modifying the Machine.Config and Web.Config files. For example, you can download an evaluation version of the Hunter Stone Web.Config Editor at http://hunterstone.com.

The <configSections> Section

The <configSections> section appears at the very top of the Machine.Config file. This section works almost like a table of contents. It contains a list of the configuration sections contained in the Machine.Config file and the .NET classes responsible for parsing them.

For example, the System.Diagnostics.DiagnosticsConfigurationHandler class parses the <system.diagnostics> section. You can add your own section handlers to this section if you want to store custom configuration information (see the “Creating a Custom Section Handler” section later in this chapter).

The <appSettings> Section

You can take advantage of the <appSettings> section to quickly add custom configuration information. For example, this is a good place to store the connection string for your database. You'll learn how to take advantage of this in the “Using the <appSettings> Section” discussion later in this chapter.

The <system.diagnostics> Section

You can add your own debug and trace listeners to this section (although tracing is handled differently in a Web Forms application). Debugging and tracing are discussed in detail in Chapter 6, “Debugging Your Web Form Pages.”

The <system.net> Section

This section contains configuration settings for network connections. For example, this section specifies that the HttpRequestCreator module is responsible for handling all http requests from Internet hosts.

The <system.net> section also contains configuration information for the proxy server used when making requests. You might need to modify this section if you run into problems when accessing a Web service through a proxy server.

The <system.web> Section

The <system.web> section contains all of the configuration settings specific to ASP.NET applications. The bulk of the remaining configuration sections can be found inside the <system.web> section.

The <trace> Element

This element enables you to configure both page- and application-level tracing. Tracing is discussed in detail in Chapter 6.

The <globalization> Element

This element specifies the character encoding used when parsing requests, responses, and code files (such as .aspx and .ascx files). By default, UTF-8 (UCS Transformation Format, 8-bit form) encoding is used. If you do not specify an encoding, your server's Regional Options locale setting is used.

You might need to modify this section if you are working in a language with a different character set.

The <httpRuntime> Element

This element enables you to configure runtime settings, such as the number of threads to use when processing incoming requests and the number of requests that can be queued before new requests are rejected.

The executionTimeout attribute enables you to specify the maximum amount of time that a Web Form page is allowed to execute before timing out. (Its default value is 90 seconds.) You'll need to modify this value if you have a page that takes a very long time to execute.

The maxRequestLength specifies the maximum amount of data allowable in a form post operation. For security reasons, by default, no one can post more than four megabytes to your server in a form post. If you want users to upload files larger than four megabytes (such as big .jpg files), you'll need to increase this value.

The <compilation> Section

The <compilation> section enables you to configure different options relevant to compiling an application. The settings in this section apply only to the presentation page, not the application code in a code-behind file.

The debug attribute enables or disables debugging for the .aspx pages (presentation pages) of your application. When debug="false", you cannot see the source code where the error occurred in the presentation page. You will need to set debug="true" to use the Visual Studio .NET debugger.

The defaultLanguage attribute sets the default language to use with presentation pages (for example, c# or vb). The default language for the .NET Framework is VB.NET. Again, this attribute does not affect code-behind files that you create in the Visual Studio .NET Code Editor.

The explicit and strict attributes only apply to VB.NET. When explicit is assigned the value true, you must declare all variables before using them. When strict is assigned the value true, lazy type conversion is not allowed. Again, these settings apply only to the presentation pages and not the code-behind files compiled by Visual Studio .NET.

Finally, the <assemblies> sub-element is used to list all the assemblies available in the presentation pages in your application. If you need to use an assembly that is not included in this list, such as System.Messaging, you'll need to add it.

Notice that the last entry is <add assembly=“*” />. This statement automatically adds all assemblies located in the application root /bin directory or the WINNTMicrosoft.NETFrameworkVersion directory. This entry is used to automatically load any custom components or controls that you create.

The <pages> Element

This section contains configuration options that apply specifically to ASP.NET pages.

The buffer attribute enables or disables page buffering. When buffering is enabled, the complete content of a page is generated before being sent to the browser. When buffering is disabled, a page is sent to the browser as it is rendered. Generally, you want to leave buffering on because it results in better overall page performance.

The enableSessionState attribute turns on or off session state or enables you to make session state read-only. When you are not using session state, you should modify this attribute to improve the performance of your application.

The enableViewState attribute enables or disables view state. You can save some bandwidth by disabling view state. However, if you disable view state, many of the Web Forms Controls will no longer function correctly.

The enableViewStateMac attribute enables or disables a message authentication code that is used to verify content stored in view state. If you are worried about users modifying the contents of the hidden view state form field, you should leave this attribute with its default value of true.

The smartNavigation attribute enables Smart Navigation. When Smart Navigation is enabled, clicking a link in a page returns you to the same position when the page reloads. This feature only works with Internet Explorer 5.0 or later. For an example of Smart Navigation, see Chapter 13, “Displaying Data with the DataGrid Control.”

The autoEventWireup attribute is false by default, and you should keep it that way when using Visual Studio .NET. If this attribute is set to true, methods declared with the proper name are automatically wired to the corresponding event. For example, a method named Button1_Click will automatically be wired to the Click event raised by the Button1 control.

The <customErrors> Section

The <customErrors> section contains configuration settings that control how errors are displayed.

The mode attribute determines whether custom error messages are displayed only for remote clients or the local machine. If you are debugging a remote server, you'll want to set the mode to the value Off. If you are debugging the local server, you'll want to set the mode to the value RemoteOnly.

The defaultRedirect attribute enables you to specify a page to which the user is automatically redirected to when an error occurs. This can be any page, including any Web Form or HTML page.

You can also list specific errors and redirect pages. For example, the following Web.Config file automatically redirects users to a page called Bad.htm when an .aspx page that does not exist is requested:

<configuration>
   <system.web>
     <customErrors defaultRedirect="genericerror.htm"
         mode="On">
         <error statusCode="404" redirect="Bad.htm"/>
     </customErrors>
  </system.web>
</configuration>

If you request a non-existent page named NotThere.aspx, you'll automatically be redirected to the Bad.htm page because requesting the NotThere.aspx page raises a “404 Not Found” status code from the server.

It's important to understand that the <customErrors> attribute only applies to pages mapped into the ASP.NET Framework. For example, if you request a normal HTML page, the <customErrors> section is ignored.

The <authentication> Section

The <authentication> section is used to configure Windows, Forms, and .NET Passport authentication. Forms authentication is discussed in detail in Chapter 16, “Securing Your Application.”

The <identity> Element

The <identity> element is used to enable or disable impersonation. By default, all ASP.NET pages run under the security context of the ASPNET account. The ASPNET account is automatically added to your server when you install the .NET Framework.

This is a change from ASP Classic. ASP Classic uses per request impersonation. If you request an ASP Classic page, the page executes under the security context of the user making the request. For anonymous users, the page executes under the security context of the IUSR_MachineName account.

If you assign the value true to the impersonate attribute, ASP.NET pages will work in the same way as ASP Classic pages. They will use per-request impersonation.

There is a third option. Instead of using the ASPNET account or per-request impersonation, you can specify a specific account. If you supply a username and password, ASP.NET pages will run under the security context of the account associated with the username.

The <authorization> Section

The <authorization> section enables you to configure Windows, Forms, or .NET Passport authorization. Forms authentication is discussed in detail in Chapter 16.

The <machineKey> Element

The <machineKey> element is used with Forms authentication. It contains encryption options to use with the Forms authentication ticket. You'll need to modify this element when using Forms authentication in a Web Farm.

The <securityPolicy> Section

This section associates named security levels with security policy files. Security policy files contain rules for assigning permissions to code.

The <sessionState> Element

This element is used to configure ASP.NET session state. For example, you can use this element to enable out-of-process session state or enable cookieless sessions. Session state is explored in detail in Chapter 17, “Maintaining Application State.”

The <httpHandlers> Section

An httpHandler is a .NET class that executes whenever you make a request for a page with a certain path. For example, a handler generates the Trace.axd page that displays application-level tracing information.

Another important handler that is listed in this section is the handler for .aspx pages—the PageHandlerFactory class. The PageHandlerFactory class is responsible for processing requests for .aspx pages.

If you want to map file extensions into the ASP.NET Framework, you need to modify the <httpHandlers> section. For example, if you want HTML pages to be processed as Web Form Pages, you need to associate the PageHandlerFactory with the .html extension by adding an entry that looks like the following:

<add verb="*" path="*.html" type="System.Web.UI.PageHandlerFactory" />

You also must modify the application mappings in the Internet Service Manager to map .html pages into the ASP.NET Framework. To do this, perform the following steps:

  1. Launch the Internet Services Manager by clicking the Start button and choosing Settings, Control Panel, Administrative Tools, Internet Services Manager.

  2. Right-click Default Web Site and select Properties.

  3. Select the Home Directory tab and click the Configuration button.

  4. Select the App Mappings tab in the Configuration dialog box.

  5. Click the Add button to open the Add/Edit Application Extension Mapping dialog box.

  6. Enter the following path in the Executable text box:

    C:WINNTMicrosoft.NETFrameworkv1.0.3705aspnet_isapi.dll
    
  7. Enter the extension .html in the Extension dialog box.

  8. Click OK to close the dialog box.

After you make these modifications, you can add ASP.NET code to an .html page in the same way as you can add code to an ASP.NET page.

Warning

The order in which you add entries to the <httpHandlers> section matters. This section uses a first match algorithm, so if you want to override the default action associated with an .html file, place your new entry near the top.

The <httpModule> Section

An httpModule is a .NET class that participates in every page request. Examples of modules include the OutputCache module responsible for page output caching and the Session module responsible for session state. Modules also implement the different authentication models built into the ASP.NET Framework.

You can create your own modules and add them to this section. For example, you can create a logging module that logs every page that users request from your Web site into a database table. To learn how to create modules, see Chapter 18, “Handling Application-Wide Events.”

The <processModel> Element

The <processModel> element has configuration settings relevant to the behavior of the ASP.NET process.

Warning

Because the <processModel> configuration settings apply to the ASP.NET process, they do not take effect until you stop and restart the ASP.NET process. You can quickly stop and restart the ASP.NET process by executing the following command from a command prompt:

iisreset

The userName attribute identifies the Windows account under which ASP.NET executes. This attribute accepts one of two special values—Machine and System. By default, the ASP.NET process executes under the Machine account, which is equivalent to the ASPNET account. Alternatively, you can specify the System account, which corresponds to the local system account.

The <processModel> element has a number of attributes that enable you to automatically restart the ASP.NET process when problems are detected. If a problem is detected, a new process is launched. All existing requests are transferred from the old process to the new process. After the requests have been transferred, the old process is shut down. If everything works right, someone requesting pages from the Web site should never notice that one process has been replaced by another.

Note

If the ASP.NET process shuts down, you lose any information stored in in-process session state and the cache. You can prevent a shutdown from clearing session state by using out-of-process session state. For more information, see Chapter 17.

For example, the timeout attribute enables you to specify an amount of time that the ASP.NET process is allowed to execute before being shut down and replaced. Oddly enough, you can actually make your Web application more stable by shutting it down periodically to start with a clean slate. For example, shutting the process down once a day will clear away any corrupted memory.

The memoryLimit attribute enables you to specify a percentage of system memory. If the ASP.NET process eats more than the specified memory limit, it is automatically shut down and replaced. This attribute is useful when you want to contain memory leaks.

The <webControls> Element

This element contains the path to the client-side JavaScript libraries used by Web Controls. For example, the JavaScript libraries used by the Web Forms Validation controls can be found at this location.

The <clientTarget> Section

This section defines several standard aliases for different types of browsers. For example, an uplevel browser is defined as Microsoft Internet Explorer 4.0. These aliases are used by Web Forms controls to enable the controls to render different content for different browsers.

The <browserCaps> Section

The <browserCaps> section is large. It contains a list of different browsers and their capabilities. The different browsers are identified by their user-agent header.

You can access the information contained in the <browserCaps> section by using the HttpBrowserCapabilities class. For example, the following code detects whether a browser supports Java applets:

C#

if (Request.Browser.JavaApplets)
{
  // Browser supports Java Applets
}

VB.NET

If Request.Browser.JavaApplets Then
  ' The browser supports Java Applets
End If

The HttpBrowserCapabilities class is exposed by the Browser property. The class uses the user-agent header to perform a lookup of the features that the browser supports from the Machine.Config file.

The <webServices> Section

This section contains configuration settings specific to XML Web services. For example, the <wsdlHelpGenerator> element specifies the location of the Web service Help Page that appears automatically when you enter the path to a Web service in a Web browser (the path to an .asmx file).

Adding Custom Configuration Information

You can place your own application configuration information in the Machine.Config or Web.Config file. Placing the information in a configuration file is useful when you want to make configuration information, such as database connection strings, available to all pages in an application.

There are two ways that you can add your custom configuration information. You can add key and value pairs to the <appSettings> section, or you can create your own section handler. Both methods are discussed in the following sections.

Using the <appSettings> Section

If you want to quickly add a single string to the Web.Config file that can be read by Web Form Pages in your application, you can take advantage of the <appSettings> section. You can add any key and value pair that you want to the <appSettings> section.

You can read the value of particular keys from the <appSettings> section in a Web Form Page by taking advantage of the ConfigurationSettings class. This class returns a collection of all the key and value pairs from the <appSettings> section.

The <appSettings> section is most commonly used to store database connection strings. In this section, you'll learn how to add a database connection string to a Web.Config file and read it from pages in your application.

First, you need to create a Web.Config file with the database connection string:

  1. Double-click the Web.Config file in the Solution Explorer window.

  2. Add the following <appSettings> section immediately below the opening <configuration> tag in the Web.Config file:

    <appSettings>
      <add key="dsn"
        value="Server=localhost;UID=sa;PWD=secret;database=pubs" />
    </appSettings>
    

    You'll need to enter the appropriate login and password for your database. Substitute your login for the UID parameter and your password for PWD parameter. Also, remember that the Web.Config file is case sensitive (even in the case of VB.NET).

  3. Click Save.

Next, we'll create a page that displays the records from the Titles database table in a DataGrid control. We'll read the database connection string from the Web.Config file that we just created.

  1. Create a new Web Form Page named TestAppSettings.aspx and click Open.

  2. In the Server Explorer window, expand the Data Connection to the Pubs database table. If a Data Connection to the Pubs database does not exist, you'll need to create one.

  3. Drag the Titles database table from the Server Explorer window onto the Designer surface. This will add an SqlConnection and an SqlDataAdapter to the page.

  4. Drag a DataSet from beneath the Data tab in the Toolbox onto the Designer surface. This will open the Add Dataset dialog box.

  5. In the Add Dataset dialog box, select Untyped Dataset and click OK.

  6. Drag a DataGrid from beneath the Web Forms tab in the Toolbox onto the Designer surface.

  7. Double-click the Designer surface. This will switch you to the Code Editor.

  8. Enter the following code for the Page_Load handler:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
    sqlConnection1.ConnectionString =
        System.Configuration.ConfigurationSettings.AppSettings[ "dsn" ];
    sqlDataAdapter1.Fill( dataSet1 );
    DataGrid1.DataSource = dataSet1;
    DataGrid1.DataBind();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      SqlConnection1.ConnectionString = ConfigurationSettings.AppSettings("dsn")
      SqlDataAdapter1.Fill(DataSet1)
      DataGrid1.DataSource = DataSet1
      DataGrid1.DataBind()
    End Sub
    
  9. Right-click the TestAppSettings.aspx page in the Solution Explorer and select Build and Browse.

After you complete these steps, the TestAppSettings.aspx page displays all the records from the Titles database table in a DataGrid control. The connection to the Pubs database is made using the connection string read from the Web.Config file.

Creating a Custom Section Handler

You can add your own configuration sections to the Machine.Config or Web.Config files. This is useful when you want to group several configuration settings into a common section. For example, you might want to create one configuration section that contains all the database connection strings that you use in your application.

Before you can create your own configuration section, however, you must create your own section handler. The section handler is used to parse your custom configuration section.

There are a number of ways that you can create your own section handler. Here, we will simply derive a new class from the NameValueSectionHandler class already included in the .NET Framework. Perform the following steps to create a new section handler named mySectionHandler:

Procedure 15.1. C# Steps

  1. Add a new class to your project by selecting Project, Add Class. Name the new class mySectionHandler.cs and click Open.

  2. Enter the following code for the mySectionHandler.cs class:

    namespace ProjectName
    {
      public class mySectionHandler:
        System.Configuration.NameValueSectionHandler
       {
       }
    }
    

Replace the placeholder ProjectName with the name of your current project in Visual Studio .NET.

Procedure 15.2. VB.NET Steps

  1. Add a new class to your project by selecting Project, Add Class. Name the new class mySectionHandler.vb and click Open.

  2. Enter the following code for the mySectionHandler.vb class:

    Public Class mySectionHandler
        Inherits System.Configuration.NameValueSectionHandler
    End Class
    

Next, we need to add our custom configuration section to the Web.Config file.

  1. Double-click the Web.Config file in the Solution Explorer window.

  2. Enter the following sections immediately below the opening <configuration> tag:

    <configSections>
      <section name="mySection"
        type="ProjectName.mySectionHandler, ProjectName" />
    </configSections>
    
    <mySection>
      <add key="FirstKey" value="Value of first key" />
      <add key="SecondKey" value="Value of second key" />
    </mySection>
    

    Replace the placeholder ProjectName with the name of your project in Visual Studio .NET.

Finally, to test our new section handler, we'll create a Web Form Page that reads the value of FirstKey and displays it in a Label control.

  1. Add a new Web Form Page named TestSectionHandler.aspx and click Open.

  2. Drag a Label control from under the Web Forms tab in the Toolbox onto the Designer surface.

  3. Double-click the Designer surface to switch to the Code Editor.

  4. Enter the following code for the Page_Load handler:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
      System.Collections.Specialized.NameValueCollection config =
        (System.Collections.Specialized.NameValueCollection)
        System.Configuration.ConfigurationSettings.GetConfig( "mySection" );
      Label1.Text = config[ "FirstKey" ];
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      Dim config As System.Collections.Specialized.NameValueCollection
      config = ConfigurationSettings.GetConfig("mySection")
      Label1.Text = config("FirstKey")
    End Sub
    
  5. Right-click the TestSectionHandler.aspx page and select Build and Browse.

When the page opens, the value assigned to FirstKey in the Web.Config file is displayed in the Label control. The value is retrieved with the help of the GetConfig() method of the ConfigurationSettings class.

Note

You might be wondering why we needed to derive a new class from the existing NameValueSectionHandler class—especially since we didn't provide any implementation code for the new class. Why not use the NameValueSectionHandler class directly in the Web.Config file?

The problem is that you cannot refer to a class in the System namespace within a Web.Config file without performing some extra work (you must supply the strong name for the class). You can, however, refer to any class contained in your application. By deriving a new class from the NameValueSectionHandler class, we've snuck the NameValueSectionHandler into our application.

Tip

You can add an attribute, named allowDefinition, to the declaration of your section handler that determines where your section can be used. This attribute can accept one of the following three values—Everywhere, MachineOnly, or MachineToApplication. For example, if you declare your section handler as follows:

<section name="mySection"
  type="myApp.mySectionHandler, myApp"
  allowDefinition="MachineOnly" />

Then you can add mySection only to a Machine.Config file and not a lower-level Web.Config file.

Advanced Configuration Topics

In this section, we'll discuss two advanced configuration topics. First, you'll learn how you can apply configuration settings in the Web.Config file to a particular file. You'll also learn how to lock down configuration settings so a developer of a particular Web application cannot change them.

Applying Configuration Settings to a Particular File

You can apply configuration settings to a particular location by taking advantage of the <location> tag. The <location> tag enables you to apply configuration settings to a particular file or directory.

For example, suppose that you want to password protect only one file in your application. You can do this by creating the following Web.Config file in the root directory of your application:

<configuration>
  <system.web>
    <authentication mode="Windows" />
  </system.web>
  <location path="secret.aspx">
    <system.web>
    <authorization>
       <deny users="*" />
    </authorization>
    </system.web>
  </location>
</configuration>

Notice that there are two <system.web> sections in this Web.Config file. The first <system.web> section applies to all files in the current directory and all subdirectories. It enables Windows authentication for the application.

The second <system.web> section appears within a <location> tag. The <location> tag restricts the scope of the <system.web> section to a file named Secret.aspx. Secret.aspx is password protected so that users can never open it.

You can use the <location> tag with any section that is declared with the allowLocation="true" attribute in the <configSections> section of the Machine.Config or Web.Config file. The allowLocation attribute is true by default.

Note

Authentication and authorization are discussed in detail in Chapter 16.

Locking Configuration Settings

You might want to lock down certain settings in the Web.Config file so that they cannot be overridden by a particular application. You can lock configuration settings by taking advantage of the <location> tag and the allowOverride attribute.

For example, you normally do not want people uploading an ASP.NET application to a production Web server that has debugging enabled. When debugging is enabled for an application, sensitive information, such as database connection strings, could be revealed to the world when runtime errors are encountered. Furthermore, the performance of an application suffers while in debug mode.

You can prevent any ASP.NET application in a Web site from executing in debug mode by adding the following Web.Config file to the wwwroot directory of the Web site:

<configuration>
<location allowOverride="false">
  <system.web>
    <compilation debug="false" />
  </system.web>
</location>
</configuration>

Any application that attempts to override this debug setting in a Web.Config file will generate a configuration error. The value of the debug setting has been locked down.

You can also use the allowOverride attribute in combination with the path attribute to lock settings for a particular application or a particular folder in an application. For example, if both the development and production Web application are located on the same server, you can use the following Web.Config file to disable debugging only for the production server:

<configuration>
<location path="ProductionApp" allowOverride="false">
  <system.web>
    <compilation debug="false" />
  </system.web>
</location>
<location path="DevelopmentApp">
  <system.web>
    <compilation debug="true" />
  </system.web>
</location>
</configuration>

Summary

In this chapter, you learned how to configure your ASP.NET applications using the Machine.Config and Web.Config configuration files.

First, you were provided with an overview of the different sections of the Machine.Config file. You learned the purpose of each of the major sections and elements of the file.

Next, you learned two methods of adding custom configuration information to the Web.Config file. You learned how to take advantage of the <appSettings> section to quickly add configuration information. You also learned how to create your own section handler that can be used with a custom configuration section.

Finally, we examined two advanced configuration topics. You learned how to use the <location> tag to apply configuration settings to a particular file or directory. You also learned how to use the allowOverride attribute to lock configuration settings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset