Using location tag in web.config
In this small article we will see how to use the <location> tag of
web.config file in your web applications. In order to understand the usage let
us consider that you have a web application that has two folders Folder1 and
Folder2. You have two databases Database1 and Database2. You want to write a
common routine such that all the pages from Folder1 should access Database1 and
all the pages from Folder2 should access Database2. How can we do that?
The first thing to be decided is - where will you store the connection strings.
Even though you can use session variables for this purpose, more elegant method
is to make use of ASP.NET configuration file - web.config. For our application
we will choose to store them in the <appSetings> of the web.config file.
Now, immediately you will ask - Can we not put two separate <add> tags in
the section for our databases? Yes, you can but this will hinder our goal of
writing a common routine as it will need to refer two distinct keys.
There are two ways to deal with this situation. The first way is to create
separate web.config files for the individual folder so that each will get
settings from their own folder. However, you then have to manage three
configuration files - one that is applicable to entire application, one for
Folder1 and one for Folder2. This method is a good choice if your individual
folders have many other distinct settings.
The second way is to use <location> tag in the root web.config file.
Location tag along with path attribute is used to mark a location to which all
the configuration settings enclosed within will be applied. Open the web.config
of your web application and add following markup to it.
<location path="Folder1">
<appSettings>
<add key="connstr" value="Provider=SQLOLEDB.1;
User ID=sa;Initial Catalog=Database1;
Data Source=localhost\netsdk" />
</appSettings>
</location>
<location path="Folder2">
<appSettings>
<add key="connstr" value="Provider=SQLOLEDB.1;
User ID=sa;Initial Catalog=Database2;
Data Source=localhost\netsdk" />
</appSettings>
</location>
Here, we have used <appSettings> section to store database connection
strings. Note how path attribute of <location> tag points to different
folders.
Now write following common routine in the pages from Folder1 and Folder2:
Public function GetConnectionString()
ConfigurationSettings.AppSettings().Item("connstr")
End sub
All the pages from Folder1 will see the Database1 in the connection string
returned where as all the pages from Folder2 will see the Database2 in the
connection string.