Thursday, November 26, 2009

ASP.Net Web.Config File

What is Web.Config File?
Web.config file, as it sounds like is a configuration file for the Asp .net web application. An Asp .net application has one web.config file which keeps the configurations required for the corresponding application. Web.config file is written in XML with specific tags having specific meanings.
What is Machine.config File?
As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications.
What can be stored in Web.config file?
There are number of important settings that can be stored in the configuration file. Here are some of the most frequently used configurations, stored conveniently inside Web.config file.
  • Database connections

  • Session States

  • Error Handling

  • Security
Database Connections:
The most important configuration data that can be stored inside the web.config file is the database connection string. Storing the connection string in the web.config file makes sense, since any modifications to the database configurations can be maintained at a single location. As otherwise we'll have to keep it either as a class level variable in all the associated source files or probably keep it in another class as a public static variable.
But if this is stored in the Web.config file, it can be read and used anywhere in the program. This will certainly save us a lot of alteration in different files where we used the old connection.
Lets see a small example of the connection string which is stored in the web.config file.

As you can see it is really simple to store the connection string in the web.config file. The connection string is referenced by a key which in this case is "ConnectionString". The value attribute of the configuration file denotes the information about the database. Here we can see that if has database name, userid and password. You can define more options if you want.
There is a very good website that deals with all sorts of connection strings. Its called , in the website you will find the connection strings for most of the databases.

Lets see how we access the connection string from our Asp .net web application.
using System.Configuration;
string connectionString = (string )ConfigurationSettings.AppSettings["ConnectionString"];

The small code snippet above is all that is needed to access the value stored inside the Web.config file.

1 comment: