Thursday, 15 March 2012

ASP.NET Web.config File Article

Applications of XML have been integrated into .NET to such an extent that XML is hardly a buzzword anymore. Microsoft, as you probably know, has taken XML into the core of its .NET framework. Not only is XML a generally accepted format for the exchange of data, it’s also used to store configuration settings.

Configuration settings for any of your ASP.NET Web applications can be stored in a simple text file. Presented in an easily understandable XML format, this file, called Web.config, can contain application-wide data such as database connection strings, custom error messages, and culture settings.
Because the Web.config is an XML file, it can consist of any valid XML tags, but the root element should always be <configuration>. Nested within this tag you can include various other tags to describe your settings. Since a Web.config file comes as a standard when you start to build a new Web application, let’s look at the default XML file generated by Visual Studio .NET:
  1. <?xml version="1.0" encoding="utf-8" ?> <br>  
  2. <configuration> <br>  
  3.   <system.web> <br>  
  4.     <compilation  <br>  
  5.          defaultLanguage="c#" <br>  
  6.          debug="true" <br>  
  7.     /> <br>  
  8.     <customErrors  <br>  
  9.     mode="RemoteOnly"  <br>  
  10.     />  <br>  
  11.     <authentication mode="Windows" />  <br>  
  12.     <authorization> <br>  
  13.         <allow users="*" /> <br>  
  14.     </authorization> <br>  
  15.     <trace <br>  
  16.         enabled="false" <br>  
  17.         requestLimit="10" <br>  
  18.         pageOutput="false" <br>  
  19.         traceMode="SortByTime" <br>  
  20.     localOnly="true" <br>  
  21.     /> <br>  
  22.     <sessionState  <br>  
  23.             mode="InProc" <br>  
  24.             stateConnectionString="tcpip=127.0.0.1:42424" <br>  
  25.             sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" <br>  
  26.             cookieless="false"  <br>  
  27.             timeout="20"  <br>  
  28.     /> <br>  
  29.     <globalization  <br>  
  30.             requestEncoding="utf-8"  <br>  
  31.             responseEncoding="utf-8"  <br>  
  32.    /> <br>  
  33.     <br>  
  34.  </system.web> <br>  
  35.  <br>  
  36. </configuration>  

Experienced ASP.NET programmers will have noticed that I’ve left out the comment tags that are generated automatically with the file. I’ve done that to provide a clear view of the XML that’s used here. Also, I’ll elaborate on each configuration tag later in this article, and this discussion will make the comment tags rather obsolete.
If you look at the example XML, you’ll notice that the <configuration> tag has only one child tag, which we call section group, the <system.web> tag. A section group typically contains the setting sections, such as: compilation, customErrors, authentication, authorization, etc. The way this works is pretty straightforward: you simply include your settings in the appropriate setting sections. If, for example, you wanted to use a different authentication mode for your Web application, you’d change that setting in the authentication section.
Apart from the standard system.web settings, you can define your own specific application settings, such as a database connection string, using the <appSettings> tag. Consequently, your most common Web.config outline would be:

  1. <configuration> <br>  
  2.   <system.web> <br>  
  3.     <! -  sections-->    <br>  
  4.   </system.web> <br>  
  5.   <appSettings> <br>  
  6.     <! -  sections -->    <br>  
  7.   </appSettings > <br>  
  8. </configuration>  
Let’s discuss the details of both section groups now.
The system.web Section Group
In this section group, you’ll typically include configuration settings that, in the pre-.NET era, you’d have set up somewhere in the IIS administration console. At Microsoft’s MSDN Library, you can find an overview of all the tags that the system.web section group understands, but, depending on the complexity of your site, you may not ever use even half of those options.
Let’s have a look at the most valuable tweaks you can make within the system.web section group, in alphabetical order.

<authentication>
The authentication section controls the type of authentication used within your Web application, as contained in the attribute mode. You’ll enter the value "None" if anyone may access your application. If authentication is required, you’ll use "Windows", "Forms" or "Passport" to define the type of authentication. For example:


  1.    <authentication mode="Windows" />  


  1.    <authorization> <br>  
  2.        <allow roles="Administrators,Users" /> <br>  
  3.        <deny users="*" /> <br>  
  4.    </authorization>  
It’s important to understand that ASP.NET’s authorization module iterates through the sections, applying the first rule that corresponds to the current user. In this example, users carrying the role Administrators or Users will be allowed access, while all others (indicated by the * wildcard) will encounter the second rule and will subsequently be denied access.

  1.    <customErrors mode="RemoteOnly" defaultRedirect="/error.html"> <br>  
  2.        <error statusCode="403" redirect="/accessdenied.html" /> <br>  
  3.        <error statusCode="404" redirect="/pagenotfound.html" /> <br>  
  4.    </customErrors>  

  1.    <globalization requestEncoding="utf-8" responseEncoding="utf-8"  <br>  
  2.        culture="nl-NL" />  

Encoding is done through the attributes requestEncoding and responseEncoding. The values should be equal in all one-server environments. In this example, the application culture is set to Dutch. If you don’t supply a culture, the application will use the server’s regional settings.

<httpRuntime>

You can use the httpRuntime section to configure a number of general runtime settings, two of which are particularly convenient.

  1.    <httpRuntime appRequestQueueLimit="100" executionTimeout="600" />  
The first attribute specifies the number of requests the server may queue in memory at heavy-traffic times. In the example, if there are already 100 requests waiting to be processed, the next request will result in a 503 error ("Server too busy").
The executionTimeout attribute indicates the number of seconds for which ASP.NET may process a request before it’s timed out.
<sessionState>

In this section of the Web.config file, we tell ASP.NET where to store the session state. The default is in the process self:

  1.    <sessionState mode="InProc" />  
Session variables are very powerful, but they have a few downsides. Information is lost when the ASP.NET process crashes, and sessions are generally useless in the case of a Web farm (multiple Web servers). In that instance, a shared session server can solve your issues. It’s beyond the scope of this article to expand on this topic, but it’s worth a mention. More information on sessionState can be found in the MSDN Library online.

<trace>

Your application’s trace log is located in the application root folder, under the name trace.axd. You can change the display of tracing information in the trace section.
The attributes you will look for initially are enabled

  1.    <trace enabled="true" localOnly="true" pageOutput="false" />  
Set localOnly to "false" to access the trace log from any client. If you set the value of pageOutput to "true", tracing information will be added to the bottom of each Web page.
The appSettings Section Group
Apart from the Website configuration settings I’ve been talking about in the preceding paragraphs, you’ll know that a programmer frequently likes to use custom application-wide constants to store information over multiple pages. The most appealing example of such a custom constant is a database connection string, but you can probably think of dozens more from your own experience.
The common denominator of these constants is that you want to retrieve their values programmatically from your code. The Web.config file provides the possibility to do so, but as a security measure, these constants have to be included in the <appSettings> section group. Just like <system.web>, <appSettings> is a direct child tag of the Web.config’s configuration root.
A typical custom section group would look something like this:

  1.    <appSettings> <br>  
  2.        <add key="sqlConn" value="Server=myPc;Database=Northwind" /> <br>  
  3.        <add key="smtpServer" value="smtp.mydomain.com" /> <br>  
  4.    </appSettings>  
The example shows that keys and values can be included in the custom application settings via an <add> tag. The way to access such a value in any of your Web pages is illustrated below:

  1.    ConfigurationSettings.AppSettings("sqlConn")  
Yes, it’s as easy as that! Note that the value of these settings is always a String format.
A Few Other Issues
I won’t go into them here, but the Web.config file can contain several other section groups besides the aforementioned system.web and appSettings, such as the configSettings group.
  • A Web application can contain more than one Web.config file. The settings in a file apply to the directory in which it’s located, and all child directories. Web.config files in child directories take precedence over the settings that are specified in parent directories.
  • Web.config files are protected by IIS, so clients cannot get to them. If you try to retrieve an existing http://mydomain.com/Web.config file, you’ll be presented with an "Access denied" error message.
  • IIS monitors the Web.config files for changes and caches the contents for performance reasons. There’s no need to restart the Web server after you modify a Web.config file.
Closing Remarks
In this article, I’ve touched upon the possibilities that the Web.config file offers the ASP.NET programmer. You can use the easily accessible XML file to define your application settings, without the hassle of using the IIS management console. With the Web.config file, ASP.NET lets you add, change and delete basic configuration settings like authentication and authorization, custom error displaying, and tracing in a straightforward manner.
Moreover, the Web.config file offers you room to define any custom key you require, such as database connection strings. What we’ve subsequently seen is that, with just one line of code, you can retrieve the information you need from any page in your application.

No comments :