Inside Web.Config configuration file in ASP.NET 3.5

No.of Views899
Bookmarked0 times
Downloads 
Votes0
By  Vishal Nayan   On  03 May 2011 04:05:51
Tag : ASP.NET , Globalization and Localization
The Web.config is main settings and configuration file for an ASP.NET web application. The file is an XML document that defines configuration information regarding the web application. The web.config file contains information that control module loading, security configuration, session configuration, and application language and compilation settings.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

It is the main settings and configuration file for an ASP.NET web application. The file is an XML document that defines configuration information regarding the web application. The web.config file contains information that control module loading, security configuration, session configuration, and application language and compilation settings.

What make up web.config file?

1)    configuration file is nested in a root <configuration> element
2)    configuration element contains a <system.web> element, which is used for ASP.NET settings
3)    Inside the <system.web> element are separate elements for each aspect of configuration.
4)    <appSettings> element can store custom settings

A typical web.config file looks like this;

<?xml version="1.0"?>
	<configuration>
		<appSettings />
		<connectionStrings />
		<system.web>
		<!-- ASP.NET configuration sections go here. -->
		</system.web>
        </configuration>

How ASP.NET 3.5 web.config file different from ASP.NET 2.0

1)    ASP.NET 3.5 is includes core ASP.NET 2.0 model i.e. version of 2.0 of the CLR, and set of new extensions that add support for new features of ASP.NET 3.5
2)    Due to this new model, ASP.NET 2.0 application can run comfortable on a server that has 3.5 or 2.0 installed.

Typically, whatever there was in ASP.NET 2.0 web.config file, is there in 3.5, with some new additions.
Let us see what are they and what they do.

Image Loading

Can we have multiple web.config files in a web application?

YES

Where can we keep these files?

In different sub-directories of your web application.

Scenario: For example, consider the web request

http://localhost/A/B/C/MyPage.aspx, where A is the root directory for the web application. In this case, multiple levels of settings come into play

How this work: ASP.NET uses configuration inheritance to handle multiple web.config files

1. The default machine.config settings are applied first.
2. The web.config settings from the computer root are applied next. This web.config file is in
The same Config directory as the machine.config file.
3. If there is a web.config file in the application root A, these settings are applied next.
4. If there is a web.config file in the subdirectory B, these settings are applied next.
5. If there is a web.config file in the subdirectory C, these settings are applied last.

So lets us take each tag one by one, and understand their purpose;

1)    Name: <location>

Description: The <location> element is an extension that allows you to specify more than one     group of settings in the same configuration file.

<configuration>
	<system.web>
		<!-- Basic configuration settings go here. -->
	</system.web>
	<location path="/Secure">
		<system.web>
			<!-- Configuration settings for the Secure subdirectory go here. -->
		</system.web>
	</location>
</configuration>

2)    Name: <customErrors>

Description: This element allows you to configure the behavior of your application in response     to various HTTP errors. The known 404 error to a page that prints a user-friendly error     message to the users of your web application by creating a section like this:

<customErrors defaultRedirect="standarderror.aspx" mode="RemoteOnly">
	<error statusCode="404" redirect="filenotfound.htm"/>
</customErrors>

Meaning of mode here;

a)    On: Indicates that custom errors are enabled. If no defaultRedirect attribute is supplied, users
    Will see a generic error.
b)    Off: Custom errors are disabled. This allows full error details to be displayed.
c)    RemoteOnly: Custom errors are shown only to remote clients while full detailed errors aredisplayed to local clients.

3)    Name: <connectionStrings>

Description: This section allows you to define database connection strings that will be used     elsewhere in your application. Seeing as connection strings need to be reused exactly to     support connection pooling and may need to be modified without recompiling the web     application, it makes perfect sense to store them in the web.config file. We can add as many     connection strings

<configuration>
		<connectionStrings>
			<add name="myConnectionString"
			connectionString=
			"Data Source=localhost;Integrated Security=SSPI;Initial 					Catalog=AIrtel;"
			providerName="System.Data.SqlClient" />
	</connectionStrings>		
</configuration>

4)    Name: <appSettings>

Description: You add custom settings to a web.config file in a special element called     <appSettings>. Here’s where the <appSettings> section fits into the web.config file:

<appSettings>
    	<add key="websiteName" value="Vishal Nayan Blog" />
    	<add key="welcomeMessage" value="Welcome, friend." />
</appSettings>

Retrieving these values from code behind is fairly simple , and you can update the config file as well from code behind;

protected void Page_Load(object sender, EventArgs e)
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

        lblSiteName.Text =
            config.AppSettings.Settings["websiteName"].Value;
        lblWelcome.Text =
            config.AppSettings.Settings["welcomeMessage"].Value;

        if (config.AppSettings.Settings["welcomeMessage"].Value.Length > 15)
        {
            config.AppSettings.Settings["welcomeMessage"].Value = "Welcome, again.";
        }
        else
        {
            config.AppSettings.Settings["welcomeMessage"].Value = "Welcome, friend.";
        }
        config.Save();
    }

So when we run this , it looks like this;

Image Loading

5)    Name: <system.web>

Description: The <system.web> element contains all the ASP.NET-specific configuration     settings. These settings configure various aspects of your web application and enable services     such as security, state management, and tracing.

It has few important elements, let us take them one by one;

1)    authentication : This element determines how you will verify a client’s identity when the client requests a page.
2)    authorization: This element controls which clients have access to the resources within the
web application or current directory.
3)    Compilation: Contains the <assemblies> element, which lists the assemblies your web
application uses. These assemblies are then made available to your code (as
long as they can be found in the Bin directory or the GAC).
4)    customErrors: Allows you to set specific redirect URLs that should be used when specific (or
default) errors occur

5)    identity: Controls the security identity of the ASP.NET application. You can use this
    setting to cause the web application to temporarily assume the identity of
    another Windows account and its permissions and restrictions. This setting is
set at the application level.

6)    httpHandlers: Defines the classes that process the HTTP requests your application receives.
    For example, requests for files with the extension .aspx are automatically handled
    by the System.Web.UI.PageHandlerFactory class, which runs the page life
cycle.

7)    httpModules: Defines classes that are given a chance to react to every request your web application receives. For example, ASP.NET’s session state and authentication
    features work through dedicated modules. Later, in the section “Extending the
HTTP Pipeline

8)    pages: Defines default page settings (most of which you can override with the Page
directive)

9)    SessionState: Configures the various options for maintaining session state for the application,such as whether to maintain it at all and where to maintain it (SQL, a
separate Windows service, and so on). This is set at the application level.

    10)  Trace: Configures tracing, an ASP.NET feature that lets you display diagnostic information
in the page (or collect it for viewing separately).

Before we wrap up everything about web.config, we will look into code by which we can encrypt web.config file.

Make a button and on onClick , write below code;

protected void btn_Click(object sender, EventArgs e)
    {
        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();
        lblInfo.Text = "web.config file saved with encrypted appSettings section.";
    }

This will encrypt our app setting values , which are now ;

<appSettings>
    <add key="websiteName" value="Vishal Nayan Blog" />
    <add key="welcomeMessage" value="Welcome, friend." />
 </appSettings>

Run the application and click to encrypt the web.config file;

Image Loading

After clicking , our app setting value in  web.config file will become like

<appSettings configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
      <CipherData>
        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAA2dU9YrCl0KQ9yq+HxDwzgQAAAACAAAAAAADZgAAqAAAABAAAACikb0f8CR1B6m2cgbtGQM7AAAAAASAAACgAAAAEAAAAO02mpJDxfDU4UDHKa0syKkoAQAADKftolRs3rpque88bIBjpZEB6wnz3Lyu6VFd/t/mICOq68KSSXToO2i2S+321wxiFN3Dv60RWnozQp2m4pLMlaVdFK/lWTjtAr+xsOp0QtLAfsJyjl+/AMocDhkLc7dcfmCOy8WJ3wNCPmapOLZRQf3KdwMo9R8iaW/4bTWfmW2l+RRi5o5IEjd6lZlFbyb9ox8yk+M7bE3vOs6noYCjJZ4OXFsUta2vwkNE5KC4gm2tKyOkMDB4Z+2/aqUaO5PULTp97mLCHjultSWcyWYaoRRESOS6LheNCcVr7Q5mO6UtvGghOBNA2zFbNSrgfBi+mMdMX4uCcDyOYUCR5PkkeleWCP8didy83qU/FVxQNd7msiSjqY596aRXHeA7y5rfK74You3lT2sUAAAAYLxUegHFaakYB8cJ57aezYcgSSk=</CipherValue>
      </CipherData>
    </EncryptedData>
  </appSettings>

Download Sample File

Download source files -4 kb

That's all and hope helps and thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
Vishal Nayan
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-02 Apr 2011
Home Page-
Blog Page-http://vishalnayan.wordpress.com
Vishal is a seasoned professional with hand on experience on Microsoft technologies. He always look for challenging assignment that allows him to learn newer technologies while utilizing his experience of project development and software engineering ethics. In spare time vishal can be found reading business and political personalities, acts as critics at columnist , writing poetries, bird watching , singing ,cooking. He have strong interests in Indian business and political arena and want to be an active one someday. He is also a part-time trainer on framework , WCF and Silverlight. reach him at vishalnayan@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top