Skip navigation

Explore Web.Config

Knowing how to customize the configuration file can help you save time and effort when building ASP.NET programs.





Explore Web.Config

Knowing how to customize the configuration file can help you save time and effort when building ASP.NET programs.


By Wayne S. Freeze


ASP.NET lets you override default options set for a Web server. These overrides are stored in a special file named Web.Config. By setting these options, you can control access to your Web pages, the type of error information returned to the user, and how session state is maintained. The Web.Config file also is a convenient place to store constants that can be retrieved at run time. In this article, you'll explore the structure of the Web.Config file and learn some cool tricks you can use in your applications.


Configure ASP.NET Applications

Microsoft uses several configuration files to control how your ASP.NET application runs. These files store the configuration using XML, and you can edit them easily using a simple editor such as Notepad. The Machine.Config file is the primary configuration file for the .NET Framework. This file is stored in c:\Windows\Microsoft.Net\Framework\version\CONFIG\ directory (be sure to replace "version" in this path with the version number you actually have). Information for all types of applications, including ASP.NET applications, is stored here.


Each Web.Config file contains information specific to an ASP.NET application and is stored in the application's root folder. The entries in the Web.Config file override the corresponding entries in the Machine.Config file, which means you never need to edit the Machine.Config file (unless you want to change the default behavior of an option for the entire Web server).


You can use multiple Web.Config files in your application. Placing a Web.Config file in your application's root folder sets default values that will be used for that directory and all subdirectories in the application. You can override the values from the root folder's Web.Config file by putting another Web.Config file in a subfolder. The values from this file will override the higher-level Web.Config files for the current folder and all folders below the current directory.


Note that if you use virtual directories in your Web site, the folders in the path part of the URL determine inheritance of the values in the Web.Config files rather than by the way the folders are physically organized. If you don't use virtual directories in Internet Information Server (IIS), this shouldn't be a problem.


The root node of both the Machine.Config file and the Web.Config file is named . Within the element are many other elements that reflect the various configuration areas. Of these elements, the and the elements are the most useful for ASP.NET applications. The element contains values that determine how the ASP.NET Application Process in the Web server runs your applications; the element contains a list of key-value pairs that can be retrieved from your application.


Key Configuration Elements

Beneath the element are elements such as , which determines how your program is compiled; , which determines how error messages are displayed; and , which specifies how state is maintained. The element specifies default values for the compilers used to compile ASP.NET applications. For instance, you can make Option Explicit and Option Strict defaults for all compiles by using this element:



You also can instruct the compiler to generate debugging information by using the debug attribute:



Of course, even if you generate debugging information, it might not display when an error occurs unless you specify the element, which controls the type of error messages displayed. By default, ASP.NET displays two types of errors: a generic error message that informs a user that an unspecified error occurred, and a detailed error message that describes the nature of the error.


By using the mode attribute, you can choose the type of error message displayed. If you set the mode attribute to On, the detailed error message always is displayed; if mode is set to Off, the generic error message is displayed. Specifying RemoteOnly (which is the default) means the detailed message displays on the local computer, but all other computers receive the generic error message.


Another feature of the element is its ability to replace the generic error message with your own error page. You can replace the generic error page by using the defaultRedirect attribute that points to your own error page:



In addition, you can specify different Web pages for different HTTP errors by using the element, which is nested inside the tag. The statusCode attribute identifies the HTTP error code, and the redirect attribute specifies the page that will display your error message:



      redirect="SL06-404.aspx" />


Trap Missing Pages

You might find it useful to create a custom error definition and a special Web page to handle the dreaded HTTP 404 error. This page should politely inform the viewer that the page he or she requested is unavailable while sending an e-mail containing the key information at the same time (see Figure 1).


Figure 1. When a missing Web page is found, this Web page displays a polite message informing the user that the requested page is missing. At the same time, this Web page generates an e-mail informing the webmaster of the missing page.


The code shown in Figure 2 generates a simple e-mail and sends it to the site's webmaster. The code uses the MailMessage class to generate a message containing the error information passed to the page in the asperrorpath parameter. Then, the code calls the SmtpMail.Send routine to send the message to the responsible party.


Sub Page_Load(Sender As Object, E As EventArgs)

  Dim msg As New System.Web.Mail.MailMessage


  msg.To = "[email protected]"

  msg.From = "[email protected]"

  msg.Subject = "Error in StartingLine web site"

  msg.Body = "This page was not found: " & _




End Sub

Figure 2. The e-mail is created by assigning values to the To, From, Subject, and Body properties of the System.Web.MailMessage class, while the System.Web.Mail.SmtpMail.Send method is used to transmit the message to the webmaster.


Maintain Session State

Maintaining session state is an important component of any Web-based application. By default, ASP.NET maintains session state by using an in-process object, but you can override it using the element. The mode attribute specifies the type of session state you should use. Setting the mode attribute to Off means the system will not maintain session-state information.


By default, mode is set to Inproc, which means the ASP.NET Application Process stores the session-state information in the local process. This is the most efficient way to store state information. But if your ASP.NET application spans multiple Web servers, the servers can't share state information. Fortunately, two other options address this limitation.


ASP.NET has a standalone state process that can be accessed from multiple servers. To use this process, you need to set the mode attribute to StateServer and specify the location of the state server by using the stateConnectionString attribute:


   stateConnectionString="tcpip=" />


The other way to maintain state information is to use a SQL Server database. In this case, you need to set mode to SQLServer and specify a database-connection string in the sqlConnectionString attribute. One advantage of using SQL Server state information is the state values are more stable than either the in-process or out-of-process state servers. If either state server crashes, the state information vanishes because the data is kept in memory. Using SQL Server, on the other hand, provides a more robust way to keep track of state information.


One other useful attribute for session state is the timeout attribute, which specifies how long state information is saved. By default, if the user doesn't access the Web server for more than 20 minutes, the state information will be discarded.


Secure Web Pages

Although defining ASP.NET page security is worthy of an article of its own, it is important to know the Web.Config file also includes security definitions. Basically, security comprises two parts: authentication, which is the method used to identify a user to the server, and authorization, which is the method that determines if a specific user may access a particular page.


You can authenticate a user in three ways: Windows authentication, Passport authentication, and forms authentication. As you would expect, Windows authentication verifies the user's identity by looking up the user's user ID and password in Windows. Passport authentication does the same thing using Microsoft's Passport tools. Forms authentication allows your own code to verify that the user ID and password are valid.


You can choose the authentication method by using the element. It has a single attribute - mode - which you can set to Windows, Forms, Passport, or None (the default). If you choose either Forms or Passport, you'll need to include the or element to include additional information needed for those approaches. You can enable Windows authentication by adding a line like this to your Web.Config file:



Once you have an authentication scheme in place, you can begin to secure individual pages by using the element. This element merely marks a section in the Web.Config file containing a series of and elements, which gives you a way to specify which users have access to the Web pages. The and elements are evaluated in the order they are listed. The first element in the list that applies to a user is the one that determines the user's access.


Both the and elements have three different attributes: users, roles, and verbs. The users attribute allows you to specify a list of users to which the element applies; the roles attribute identifies the list of NT Security groups; and the verbs attribute defines which HTTP verbs (such as Get, Head, and Post) this element controls. If you use the users attribute, you can use two special values in place of a username: An asterisk (*) means the element applies to all users, and a question mark (?) refers to all anonymous users.


You can use the and elements to specify a simple security structure in which all the ASP.NET pages in the Web site's root folder are unrestricted and the restricted pages are stored in a subfolder. Remember that the Web.Config file applies to the current folder and all subfolders that do not have their own Web.Config file. Therefore, including these elements in the root folder's Web.Config file would allow all users to access the Web site:




Then, in the secure folder's Web.Config file, the following elements would deny access to all anonymous users but would permit all users who have been authenticated successfully to access the site:





Get Application Constants

Perhaps the most compelling reason for creating a custom Web.Config file is the element. You can use this element to specify application-wide constants. You can use many techniques to specify application constants, but is the most flexible.


Let's assume you use one computer to develop your ASP.NET applications and another to run them. To move your application from one machine to another, you need to locate and change your database-connection strings in every application. If you store your database-connection strings in the Web.Config file, however, you can create two versions of the file: one for your development computer and one for your production computer. This way, your application adapts to either machine automatically.


The element is specified either at the same level as the element or directly beneath the element. Each constant is stored beneath the element by using the element. The element requires two attributes - key and value. The key attribute specifies the name of the constant, and the value attribute specifies the constant's value. This example shows how you might define a couple constants for your application:



     value="Data Source=localhost;Integrated Security=SSPI;

      Initial Catalog=VeTour" />



In order to retrieve these constants, you need to import the System.Configuration namespace. Then you can use the AppSettings method of the ConfigurationSettings class. Because this is a static method, you don't need to create an instance of the class to use it. This means any time you need the constant, you can use code like this:


TextBox1.Text = ConfigurationSettings.AppSettings( _



Of course, because the constants are strings, you will need to do any necessary conversions for non-string values, but it's a small price to pay for this kind of flexibility.


Please drop me an e-mail at mailto:[email protected] if you have any questions or comments about this article. I love hearing from my readers.


The files and sample application referenced in this article are available for download.


Wayne S. Freeze is a full-time author with more than a dozen books to his credit, including Windows Game Programming with Visual Basic and DirectX (Que) and Unlocking OLAP with SQL Server and Excel 2000 (Hungry Minds). He has more than 25 years of experience using all types of computers, from small, embedded microprocessor control systems to large-scale IBM mainframes. Wayne has a master's degree in management information systems as well as degrees in computer science and engineering. Visit his Web site at or e-mail him at mailto:[email protected].


Tell us what you think! Please send any comments about this article to [email protected]. Please include the article title and author.




Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.