Click here to Skip to main content
Click here to Skip to main content

Web.config File - ASP.NET

, 18 Dec 2011
Rate this:
Please Sign up or sign in to vote.
Complete description about the ASP.NET configuration. This article helps you to understand the web.config file in a better way and also helps you to program against it.

Introduction

The time you start developing your web application until you finish the application, you will more often use the Web.config file not only for securing your application but also for wide range of other purposes which it is intended for. ASP.NET Web.config file provides you a flexible way to handle all your requirements at the application level. Despite the simplicity provided by the .NET Framework to work with web.config, working with configuration files would definitely be a task until you understand it clearly. This could be one of the main reasons that I started writing this article.

This article would be a quick reference for the professional developers and for those who just started programming in .NET. This article would help them to understand the ASP.NET configuration in an efficient way. The readers may skip the reading section "Authentication, Authorization, Membership Provider, Role Provider and Profile Provider Settings", as most of them are familiar with those particular settings.

Background

In this article, I am going to explain about the complete sections and settings available in the Web.config file and how you can configure them to use in the application. In the later section of the article, we will see the .NET classes that are used to work with the configuration files. The contents of the articles are summarized below:

  1. Web.config sections/settings
  2. Reading Web.config
  3. Writing or manipulating Web.config
  4. Encrypting the Web.config and
  5. Creating your own Custom Configuration Sections

Points to be Remembered

ASP.NET Web.config allows you to define or revise the configuration settings at the time of developing the application or at the time of deployment or even after deployment. The following are brief points that can be understood about the Web.config file:

  • Web.config files are stored in XML format which makes us easier to work with.
  • You can have any number of Web.config files for an application. Each Web.config applies settings to its own directory and all the child directories below it.
  • All the Web.config files inherit the root Web.config file available at the following location systemroot\Microsoft.NET\Framework\versionNumber\CONFIG\Web.config location
  • IIS is configured in such a way that it prevents the Web.config file access from the browser.
  • The changes in Web.config don’t require the reboot of the web server.

Web.config Settings

Before we start working with configuration settings of ASP.NET, we see the hierarchy of the Web.config file.

<configuration>

        <configSections>
            <sectionGroup>
            </sectionGroup>
        </configSections>

        <system.web>
        </system.web>

        <connectionStrings>
        </connectionStrings>

        <appSettings>
        </appSettings>
        …………………………………………………………………………………………………………
        …………………………………………………………………………………………………………
        …………………………………………………………………………………………………………
        …………………………………………………………………………………………………………
        …………………………………………………………………………………………………………

</configuration>

So from the above tree structure, we can understand that the configuration tag is the root element of the Web.config file under which it has all the remaining sub elements. Each element can have any number of attributes and child elements which specify the values or settings for the given particular section. To start with, we’ll see the working of some of the most general configuration settings in the Web.config file.

system.web

In the configuration hierarchy, the most common thing we will work with is the system.web section. Now we look at some of the child sections of the system.web section of Web.config file.

Compilation Settings

If you are using Visual Studio 2010, probably the only available section of Web.config file by default is Compilation section. If you want to specify the target framework or if you need to add an assembly from the Global Assembly Cache (GAC) or if you want to enable the debugging mode of the application, you can take Compilation settings as granted for these tasks. The following code is used to achieve the discussed settings:

<system.web
	<compilation
                 debug="true" strict="true" explicit="true" batch="true"
                 optimizeCompilations="true" batchTimeout="900"
                 maxBatchSize="1000" maxBatchGeneratedFileSize="1000"
                 numRecompilesBeforeAppRestart="15" defaultLanguage="c#"
                 targetFramework="4.0" assemblyPostProcessorType="">
	<assemblies>
		<add assembly="System, Version=1.0.5000.0, Culture=neutral,
                  PublicKeyToken=b77a5c561934e089"/>
	</assemblies>

</compilation>
</system.web>

Under the assemblies element, you are supposed to mention the type, version, culture and public key token of the assembly. In order to get the public key token of an assembly, you need to follow the below mentioned steps:

  1. Go to Visual Studio tools in the start menu and open the Visual Studio command prompt.
  2. In the Visual Studio command prompt, change the directory to the location where the assembly or .dll file exists.
  3. Use the following command, sn –T itextsharp.dll.
  4. It generates the public key token of the assembly. You should keep one thing in mind that only public key token is generated only for the assemblies which are strongly signed.

Example

C:\WINNT\Microsoft.NET\Framework\v3.5> sn -T itextsharp.dll
Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key token is badfaf3274934e0

Explicit and sample attributes are applicable only to VB.NET and C# compiler however ignores these settings.

Page Settings

Ok, by this time, we have got familiar with the Web.config file and we have seen the settings of Compilation Sections, now we will see the settings of a page. As an ASP.NET application consists of several number of pages, we can set the general settings of a page like sessionstate, viewstate, buffer, etc., as shown below:

<pages buffer ="true" styleSheetTheme="" theme ="Acqua"
              masterPageFile ="MasterPage.master"
              enableEventValidation="true"> 

By using the MasterPageFile and theme attributes, we can specify the master page and theme for the pages in web application.

Custom Error Settings

The next section of Web.config file, we are going to look around is Custom Error settings, by the name itself it is clear that we can configure the settings for the application level errors in these section. Now we will see the description of the customErrors section of the Web.config from the below mentioned code snippet.

<customErrors defaultRedirect ="Error.aspx" mode ="Off">
   <error statusCode ="401" redirect ="Unauthorized.aspx"/>
</customErrors>    

The customErrors section consists of defaultRedirect and mode attributes which specify the default redirect page and the on/off mode respectively.
The subsection of customErrors section allows redirecting to specified page depending on the error status code.

  • 400 Bad Request
  • 401 Unauthorized
  • 404 Not Found
  • 408 Request Timeout

For a more detailed report of status code list, you can refer to this URL:

Location Settings

If you are working with a major project, probably you might have numerous numbers of folders and sub-folders, at this kind of particular situation, you can have two options to work with. First thing is to have a Web.config file for each and every folder(s) and Sub-folder(s) and the second one is to have a single Web.config for your entire application. If you use the first approach, then you might be in a smoother way, but what if you have a single Web.config and you need to configure the sub-folder or other folder of your application, the right solution is to use the "Location" tag of "system.web" section of Web.config file. However you can use this tag in either of the discussed methods.

The following code shows you to work with Location settings:

<location path="Login.aspx">
	<system.web>
		<authorization>
	         <allow users="*"/>
		</authorization>
	</system.web>
</location>
<location path ="Uploads">
    <system.web>
	<compilation debug = "false">
    </system.web>
</location>

In a similar way, you can configure any kind of available settings for any file/folder using the location tag.

Session State and View State Settings

As we all know, the ASP.NET is stateless and to maintain the state we need to use the available state management techniques of ASP.NET. View state and session state are among them. For complete information about view state and Session State and how to work with, there are some excellent articles in CodeProject, which you can refer here:

Now we'll see the Web.config settings of View State and Session State:
View State can be enabled or disabled by using the following page settings in the web.config file.

<Pages EnableViewState="false" />

Session state settings for different modes are as shown below:

<sessionState mode="InProc" />
<sessionState mode="StateServer"
stateConnectionString= "tcpip=Yourservername:42424" />
<sessionState mode="SQLServer" sqlConnectionString="cnn" />

HttpHandler Settings

HttpHandler is a code that executes when an http request for a specific resource is made to the server. For example, request an .aspx page the ASP.NET page handler is executed, similarly if an .asmx file is requested, the ASP.NET service handler is executed. An HTTP Handler is a component that handles the ASP.NET requests at a lower level than ASP.NET is capable of handling.

You can create your own custom http handler, register it with IIS and receive notice whenever a request is made. For doing this, you just need to create a class which implements IHttpHanlder and then you need to add the following section of configuration settings in the web.config file. For this demonstration, I have created a sample imagehandler class which displays a JPG image to the browser.You can go through the imagehandler class code in the sample download code.

<httpHandlers>
    <add verb="*" path="*.jpg" type="ImageHandler"/>
    <add verb="*" path="*.gif" type="ImageHandler"/>
</httpHandlers/>

HttpModule Settings

HttpModule is a class or an assembly that implements the IHttpModule interface that handles the application events or user events. You can too create your own custom HttpModule by implementing the interface and configure it with ISS. The following settings show the HttpModules configuration in the web.config.

<httpModules>
      <add type ="TwCustomHandler.ImageHandler"
           name ="TwCustomHandler"/>
      <remove name ="TwCustomHandler"/>
      <clear />
</httpModules>

Authentication, Authorization, Membership Provider, Role Provider and Profile Provider Settings

These settings are directly available in the web.config file if you have created the ASP.NET application by using the Visual Studio 2010. I'm not going to elaborate them as there are lot of articles in CodeProject describing the functionality and use of these settings and for further information you can refer to them. Some of the links are here:

Authentication Settings

<authentication mode="Forms">
     <forms cookieless="UseCookies" defaultUrl="HomePage.aspx"
                    loginUrl="UnAuthorized.aspx" protection="All" timeout="30">
      </forms>
</authentication>    

Authorization Settings

<authorization
        <allow roles ="Admin"/>
        <deny users ="*"/>
</authorization>        

Membership Provider Settings

<membership defaultProvider="Demo_MemberShipProvider">
	<providers>
	   <add name="Demo_MemberShipProvider"
	        type="System.Web.Security.SqlMembershipProvider"
	        connectionStringName="cnn"
	        enablePasswordRetrieval="false"
	        enablePasswordReset="true"
	        requiresQuestionAndAnswer="true"
	        applicationName="/"
	        requiresUniqueEmail="false"
	        passwordFormat="Hashed"
	        maxInvalidPasswordAttempts="5"
	        minRequiredPasswordLength="5"
	        minRequiredNonalphanumericCharacters="0"
	       passwordAttemptWindow="10" passwordStrengthRegularExpression="">
	</providers>
</membership>

Role Provider Settings

<roleManager enabled="true" cacheRolesInCookie="true"
cookieName="TBHROLES" defaultProvider="Demo_RoleProvider">
              <providers>
                  <add connectionStringName="dld_connectionstring"
                  applicationName="/" name="Demo_RoleProvider"
                  type="System.Web.Security.SqlRoleProvider, System.Web,
                  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
             </providers>
</roleManager>

Profile Provider Settings

<profile defaultProvider="Demo_ProfileProvider">
    <providers>
	<add name="Demo_ProfileProvider" connectionStringName="cnn"
	applicationName="/" type="System.Web.Profile.SqlProfileProvider,
	System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </providers>
    <properties>
	<add name="Name" type="String"/>
	<add name="DateofBirth" type="DateTime"/>
	<add name="Place" type="string"/>
    </properties>
</profile>

AppSettings

In the above section, we have seen the settings available in system.web tag, now we will see the available settings in appSettings section.
appSettings element helps us to store the application settings information like connection strings, file paths, URLs, port numbers, custom key value pairs, etc.
The following code snippet shows the example of appSettings Section:

<appSettings>
	<add key="AppKey" value="APLJI12345AFAFAF89999BDFG"/>
</appSettings>

connectionStrings

The most common section of web.config file the connectionStrings sections allows you to store multiple connection strings that are used in the application. The connectionStrings tag consists of child element with attributes name and connectionstring which is used to identify the connectionstring and the other is used to connect to the database server respectively.

The general connectionstring settings are shown below:

<connectionStrings>
    <add name ="cnn" connectionString ="Initial Catalog = master; 
		Data Source =localhost; Integrated Security = true"/>
</connectionStrings>

ConfigSections

ConfigSections helps you to create your own custom configuration section that can be used with the web.config file. We look at this in the later section of the article, for the time being, we can have look at the configsection settings. ConfigSections should be declared just below the configuration (parent element) otherwise it is going through you an error.

<configSections>
    <sectionGroup name="pageAppearanceGroup">
      <section
        name="pageAppearance"
        type="PageAppearanceSection"
        allowLocation="true"
        allowDefinition="Everywhere"
      />
 </sectionGroup>
 </configSections>

Programmatically Accessing the Web.config File

We can use the C# classes to read and write the values to the Web.config file.

Reading appSettings values

The following code is used to read the appSettings values from Web.config file. You can use either of the methods shown below:

//Method 1:
        string key = ConfigurationManager.AppSettings["AppKey"];
        Response.Write(key);

//Method 2:
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
        KeyValueConfigurationElement Appsetting = config.AppSettings.Settings["AppKey"];
        Response.Write(Appsetting.Key + " <br/>" + "Value:" + Appsetting.Value);

Reading connectionstring values

The following code is used to read the connectionstring values from Web.config file. You can use either of the methods shown below:

//Method 1:
        string cnn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

//Methods 2:
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
        ConnectionStringSettings cnnstring;

        if (config.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            cnnstring = config.ConnectionStrings.ConnectionStrings["conn"];
            if (cnnstring != null)
                Response.Write("ConnectionString:" + cnnstring.ConnectionString);
            else
                Response.Write(" No connection string");
        }

Reading configuration section values

The following code is used to read the configuration section values from Web.config file. The comments in the code will help you to understand the code:

// Intialize System.Configuration object.
Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
//Get the required section of the web.config file by using configuration object.
CompilationSection compilation = 
	(CompilationSection)config.GetSection("system.web/compilation");
//Access the properties of the web.config
Response.Write("Debug:"+compilation.Debug+"<br/>""+
		"Language:"+compilation.DefaultLanguage);

Update the configuration section values

The following code is used to read the configuration section values from Web.config file:

Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
//Get the required section of the web.config file by using configuration object.
CompilationSection compilation = 
	(CompilationSection)config.GetSection("system.web/compilation");
//Update the new values.
compilation.Debug = true;
//save the changes by using Save() method of configuration object.
if (!compilation.SectionInformation.IsLocked)
{
    config.Save();
    Response.Write("New Compilation Debug"+compilation.Debug);
}
else
{
    Response.Write("Could not save configuration.");
}

Encrypt Configuration Sections of Web.config File

As we have already discussed that IIS is configured in such a way that it does not serve the Web.Config to browser, but even in some such situation to provide more security, you can encrypt some of the sections of web.config file. The following code shows you the way to encrypt the sections of web.config file:

Configuration config = WebConfigurationManager.OpenWebConfiguration
			(Request.ApplicationPath);
ConfigurationSection appSettings = config.GetSection("appSettings");
if (appSettings.SectionInformation.IsProtected)
{
    appSettings.SectionInformation.UnprotectSection();
}
else
{
    appSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
}
config.Save();    

Custom Configuration Section in Web.config

I have thought twice before I could put this section of content in this article, as there are a lot of wonderful articles explaining this topic, but just to make this article as complete, I have included this topic too.

Create Custom Configuration Section

The ConfigurationSection class helps us to extend the Web.config file in order to fulfill our requirements. In order to have a custom configuration section, we need to follow the below steps:

Before we actually start working with it, we will have a look at the section settings. We need to have a ProductSection element with child elements girdSettings and color. For this purpose, we will create two classes with the child elements which inherits ConfigurationElement as shown below:

public class GridElement : ConfigurationElement
{
    [ConfigurationProperty("title", DefaultValue = "Arial", IsRequired = true)]
    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", 
			MinLength = 1, MaxLength = 60)]
    public String Title
    {
        get
        {
            return (String)this["title"];
        }
        set
        {
            this["title"] = value;
        }
    }

    [ConfigurationProperty("count", DefaultValue = "10", IsRequired = false)]
    [IntegerValidator(ExcludeRange = false, MaxValue = 30, MinValue = 5)]
    public int Count
    {
        get
        { return (int)this["count"]; }
        set
        { this["size"] = value; }
    }
}

public class ColorElement : ConfigurationElement
{
    [ConfigurationProperty("background", DefaultValue = "FFFFFF", IsRequired = true)]
    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;
		'\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)]
    public String Background
    {
        get
        {
            return (String)this["background"];
        }
        set
        {
            this["background"] = value;
        }
    }

    [ConfigurationProperty("foreground", DefaultValue = "000000", IsRequired = true)]
    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;
		'\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)]
    public String Foreground
    {
        get
        {
            return (String)this["foreground"];
        }
        set
        {
            this["foreground"] = value;
        }
    }

} 

... and then we will create a class called ProductSection, for the root element which includes the above child elements.

public class ProductSection : ConfigurationSection
{
    [ConfigurationProperty("gridSettings")]
    public GridElement gridSettings
    {
        get
        {
            return (GridElement)this["gridSettings"];
        }
        set
        { this["gridSettings"] = value; }
    }

    // Create a "color element."
    [ConfigurationProperty("color")]
    public ColorElement Color
    {
        get
        {
            return (ColorElement)this["color"];
        }
        set
        { this["color"] = value; }
    }
}

Then finally, we will configure these elements in Web.config file as shown below:

 <configSections>
      <section name ="ProductSection" type ="<ProductSection"/>
  </configSections>

  <ProductSection>
    <gridSettings title ="Latest Products" count ="20"></gridSettings>
    <color background="FFFFCC" foreground="FFFFFF"></color>
  </ProductSection>
Access Custom Configuration Section

The following code is used to access the custom configuration section:

ProductSection config = (ProductSection)ConfigurationManager.GetSection("ProductSection");
string color =config.Color.Background;
string title =config.gridSettings.Title;
int count = config.gridSettings.Count;

Conclusion

In this article, we have learned about the ASP.NET configuration file and we have seen almost all the available and frequently used settings of web.config file. I hope you enjoyed reading this article and this article might have helped you in completing your tasks in some way. Any comments, suggestions and feedback are always welcome, which will help me to write more articles and improve the way in which I present the articles.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

S V Saichandra
Software Developer GSS Infotech Ltd.
India India
S V Sai Chandra is a Software Engineer from Hyderabad Deccan. He started Embedded Programing in his college days and now he is a Web Developer by Profession. He Loves coding and his passion is always been towards Microsoft Technologies. Apart from coding his other hobbies include reading books, painting and hang out with friends is his most favorite past time hobby.
He blogs at
http://technowallet.blogspot.com
Technical Skills:
C#,Ado.Net,Asp.Net,Sql Server,JavaScript,XML,Web services.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 3 PinmemberKrismaly17-Apr-14 9:47 
GeneralMy vote of 5 Pinmemberaditya_bokade1-Dec-13 0:37 
QuestionThanks PinmemberAmir Mehrabi-Jorshari28-Oct-13 20:09 
Questiongood articel PinmemberVivek Doddaguni14-Oct-13 13:27 
QuestionLocation Tag Pinmember VICK9-Oct-13 19:58 
QuestionMy Vote Of Five PinmemberPratik Bhuva12-Sep-13 20:57 
QuestionMy Vote Of 5 Pinmemberhaivanguyen21-Jul-13 18:53 
GeneralMy vote of 5 PinmemberАslam Iqbal15-May-13 1:01 
GeneralMy vote of 5 PinmemberCarsten V2.024-Apr-13 5:17 
GeneralMy vote of 5 PinmemberVikZ919-Apr-13 2:36 
GeneralMy vote of 5 PinmemberDalbirS7-Apr-13 23:11 
GeneralMy vote of 4 PinmemberSubbu Kakarla27-Feb-13 20:38 
QuestionWeb.config PinmemberMember 987096327-Feb-13 18:47 
GeneralMy vote of 3 PinmemberSalman M Sayed14-Jan-13 23:04 
GeneralMy vote of 5 Pinmemberhemantrautela5-Jan-13 19:25 
GeneralMy vote of 5 Pinmembersarathkumarnallathambi17-Dec-12 20:04 
QuestionVery Good Article (5)! It answered many of my questions. Thanks Mr. Chandra PinmemberJack.LaPenta26-Dec-12 6:39 
GeneralMy vote of 3 Pinmemberrajnish2patel30-Nov-12 8:38 
GeneralMy vote of 5 Pinmemberpbsbalu28-Nov-12 0:58 
Questiongood PinmemberS.K.Tripathi17-Sep-12 17:59 
GeneralMy vote of 5 Pinmemberj_matych21-Aug-12 5:17 
GeneralMy vote of 5 PinmemberRahul Rajat Singh27-Jun-12 1:16 
Generalthanks my problem solved........... Pinmemberpiyushw23-May-12 22:17 
GeneralMy vote of 5 Pinmembererankitkhare16-May-12 0:12 
GeneralMy vote of 5 Pinmemberambarishtv21-Jan-12 23:31 
GeneralMy vote of 5 PinmemberRa-one12-Jan-12 18:27 
GeneralMy vote of 4 Pinmembervtirumalaraju26-Dec-11 22:09 
GeneralMy vote of 5 PinmemberMonjurul Habib26-Dec-11 6:46 
GeneralRe: My vote of 5 PinmemberS V Saichandra26-Dec-11 16:40 
GeneralMy vote of 4 Pinmemberbrijgogogo25-Dec-11 5:24 
GeneralRe: My vote of 4 PinmemberS V Saichandra26-Dec-11 16:40 
GeneralMy vote of 5 PinmemberMohammad_Denmark20-Dec-11 0:11 
GeneralRe: My vote of 5 PinmemberS V Saichandra26-Dec-11 16:41 
GeneralMy vote of 5 Pinmemberlovejun18-Dec-11 20:04 
GeneralRe: My vote of 5 PinmemberS V Saichandra26-Dec-11 16:41 
GeneralMy vote of 1 PinmemberSelvin18-Dec-11 4:32 
GeneralRe: My vote of 1 PinmemberMember 368155619-Dec-11 5:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140902.1 | Last Updated 18 Dec 2011
Article Copyright 2011 by S V Saichandra
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid