0% found this document useful (0 votes)
96 views16 pages

Chapter 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views16 pages

Chapter 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 3

ASP.Net Intrinsic Objects and State Management


Intrinsic Objects:
ASP.NET provides intrinsic objects to enable low-level access to the Web application
framework. These objects allow you to work directly with the underlying HTTP streams and
server, session, and application objects. The intrinsic objects can be accessed in a Web form
through the properties of the Page

The HttpRequest Object


The HttpRequest object represents the incoming request from the client to the Web server. The
request from the client can come in two ways GET or POST. GET attaches the data with the
URL, whereas POST embeds the data within the HTTP request body.
The HttpRequest intrinsic object can be accessed by the Request property of the Page class.
Following tables shows list the properties and methods of the HttpRequest class, respectively.
Note that all the properties except the Filter property of the HttpRequest class are read-only.

Properties of the HttpRequest Class


Property Description
AcceptTypes Specifies the MIME types that the client browser accepts
ApplicationPath Represents the application's virtual application root path on the
server
Browser Provides access to the capabilities and characteristics of the
requesting browser
ClientCertificate Represents the certificate, if any, sent by the client for secure
communications
ContentEncoding Represents the character encoding (such as UTF7, ASCII , and so
on) for the entity body
ContentLength Specifies the length in bytes of the request
ContentType Specifies the MIME type of the incoming request
Cookies Represents the cookies collection that is sent by the client to the
server
CurrentExecutionFilePath Specifies the virtual path of the current executing page on the Web
server
FilePath Specifies the virtual path of the file on the Web server
Files Represents the file collection that is posted by the client to the
Web server
Filter Represents a stream that is applied as a filter on the incoming
request
Form Specifies the contents of a form posted to the server
Headers Represents the HTTP headers included with the incoming request
HttpMethod Represents the method of the HTTP request (for example, GET,
POST , or HEAD )
InputStream Represents the stream that contains the incoming HTTP request
body
IsAuthenticated Indicates whether the client has been authenticated to the Web
site
IsSecureConnection Indicates whether the client connection is over a secure HTTPS
connection
Params Represents the form, query string, cookies, and server variables
collection of the current request
Path Specifies the virtual path of the current request, along with
additional path information
PathInfo Specifies the additional path information of the current request
PhysicalApplicationPath Specifies the physical file system path of the application's root
directory
PhysicalPath Specifies the physical file system path of the current request on the
Web server
QueryString Represents the query string collection sent by the client to the Web
server through the URL
RawUrl Specifies the URL portion of the current request, excluding the
domain information
RequestType Represents the type of request ( GET or POST ) made by the client
ServerVariables Represents the collection of Web server variables
TotalBytes Represents the total number of bytes posted to the server in the
current request
Url Specifies information about the current URL request
UrlReferrer Specifies the URL of the client's previous request that linked to the
current URL request
UserAgent Represents the browser being used by the client
UserHostAddress Represents the IP address of the requesting client's machine
UserHostName Represents the domain name system (DNS) name of the requesting
client's machine
UserLanguages Specifies the languages preferred by the client's browser

Methods of the HttpRequest Class


ethod Description
Method Description
BinaryRead() Reads the specified number of bytes from the request stream. This
method is provided for backward compatibility; you should use
the InputStream property instead.
MapImageCoordinates() Returns the coordinates of a form image that is sent to the server in
the current request.
MapPath() Returns the physical file system path of the file for a specified virtual
path of a Web server.
SaveAs() Saves the current HTTP request into a disk file, with an option to
include or exclude headers.

Response Object
The Response object represents the server's response to the client request. It is an instance of
the System.Web.HttpResponse class.
In ASP.NET, the response object does not play any vital role in sending HTML text to the client,
because the server-side controls have nested, object oriented methods for rendering
themselves.
However, the HttpResponse object still provides some important functionalities, like the
cookie feature and the Redirect() method. The Response.Redirect() method allows
transferring the user to another page, inside as well as outside the application. It requires a
round trip.
Properties and Methods of the Response Object
Property Description
Buffer Gets or sets a value indicating whether to buffer the output and
send it after the complete response is finished processing.
BufferOutput Gets or sets a value indicating whether to buffer the output and
send it after the complete page is finished processing.
Charset Gets or sets the HTTP character set of the output stream.
ContentEncoding Gets or sets the HTTP character set of the output stream.
ContentType Gets or sets the HTTP MIME type of the output stream.
Cookies Gets the response cookie collection.
Expires Gets or sets the number of minutes before a page cached on a
browser expires.
ExpiresAbsolute Gets or sets the absolute date and time at which to remove cached
information from the cache.
HeaderEncoding Gets or sets an encoding object that represents the encoding for the
current header output stream.
Headers Gets the collection of response headers.
IsClientConnected Gets a value indicating whether the client is still connected to the
server.
Output Enables output of text to the outgoing HTTP response stream.
OutputStream Enables binary output to the outgoing HTTP content body.
RedirectLocation Gets or sets the value of the Http Location header.
Status Sets the status line that is returned to the client.
StatusCode Gets or sets the HTTP status code of the output returned to the
client.
StatusDescription Gets or sets the HTTP status string of the output returned to the
client.
SubStatusCode Gets or sets a value qualifying the status code of the response.
SuppressContent Gets or sets a value indicating whether to send HTTP content to the
client.

The following table provides a list of some important methods:


Method Description
AddHeader Adds an HTTP header to the output stream. AddHeader is
provided for compatibility with earlier versions of ASP.
AppendCookie Infrastructure adds an HTTP cookie to the intrinsic cookie
collection.
AppendHeader Adds an HTTP header to the output stream.
AppendToLog Adds custom log information to the InterNET Information Services
(IIS) log file.
BinaryWrite Writes a string of binary characters to the HTTP output stream.
ClearContent Clears all content output from the buffer stream.
Close Closes the socket connection to a client.
End Sends all currently buffered output to the client, stops execution of
the page, and raises the EndRequest event.
Equals(Object) Determines whether the specified object is equal to the current
object.
Flush Sends all currently buffered output to the client.
GetType Gets the Type of the current instance.
Pics Appends a HTTP PICS-Label header to the output stream.
Redirect(String) Redirects a request to a new URL and specifies the new URL.
Redirect(String, Redirects a client to a new URL. Specifies the new URL and
Boolean) whether execution of the current page should terminate.
SetCookie Updates an existing cookie in the cookie collection.
ToString Returns a String that represents the current Object.
TransmitFile(String) Writes the specified file directly to an HTTP response output
stream, without buffering it in memory.
Write(Char) Writes a character to an HTTP response output stream.
Write(Object) Writes an object to an HTTP response stream.
Write(String) Writes a string to an HTTP response output stream.
WriteFile(String) Writes the contents of the specified file directly to an HTTP
response output stream as a file block.
WriteFile(String, Writes the contents of the specified file directly to an HTTP
Boolean) response output stream as a memory block.

The HttpServerUtility Object


The HttpServerUtility object contains utility methods and properties to work with the Web
server. It also contains methods to enable HTML/URL encoding and decoding, execute or
transfer to an ASPX page, create COM components , and so on. The Server property of
the Page class provides access to the HttpServerUtility object.

Properties of ServerUtility Class


Property Description
MachineName Returns the name of the server that hosts the Web application
ScriptTimeout Indicates the number of seconds that are allowed to elapse when processing the
request before a timeout error is sent to the client

Methods of the HttpServerUtility Class


Method Description
ClearError() Clears the last exception from memory
CreateObject() Creates a COM object on the server
CreateObjectFromClsid() Creates a COM object on the server identified by a specified class
identifier (CLSID)
Execute() Executes an ASPX page within the current requested page
GetLastError() Returns the last exception that occurred on the Web server
Method Description
HtmlDecode() Decodes a string that has been previously encoded to eliminate
invalid HTML characters
HtmlEncode() Encodes a string converting any characters that are illegal in HTML
for transmission over HTTP
MapPath() Returns the physical path for a specified virtual path on a Web server
Transfer() Allows the transfer of ASPX page execution from the current page to
another ASPX page on the same Web server
UrlDecode() Decodes a string that has been previously encoded to eliminate
invalid characters for transmission over HTTP in a URL
UrlEncode() Encodes a given string for safe transmission over HTTP
UrlPathEncode() Encodes the path portion of the URL string for safe transmission over
HTTP

HttpApplicationState
The ASP.NET application is the collection of all web pages, code and other files within a single
virtual directory on a web server. When information is stored in application state, it is available
to all the users. To provide for the use of application state, ASP.NET creates an application state
object for each application from the HTTPApplicationState class and stores this object in server
memory. This object is represented by class file global.asax. Application State is mostly used to
store hit counters and other statistical data, global application data like tax rate, discount rate
etc. and to keep the track of users visiting the site.

The HttpApplicationState class has the following properties:


Itemname: - The value of the application state item with the specified name.
Count:- This is the default property of the HttpApplicationState class. The number of items in
the application state collection.

The HttpApplicationState class has the following methods:


Addname, value Adds an item to the application state collection.
Clear Removes all the items from the application state collection.
Removename Removes the specified item from the application state collection.
RemoveAll Removes all objects from an HttpApplicationState collection.
RemoveAt Removes an HttpApplicationState object from a collection by index.
Lock Locks the application state collection so only the current user can access it.
Unlock Unlocks the application state collection so all the users can access it.

HttpSessionState
When a user connects to an ASP.NET website, a new session object is created. When session
state is turned on, a new session state object is created for each new request. This session state
object becomes part of the context and it is available through the page. Session state is
generally used for storing application data such as inventory, supplier list, customer record, or
shopping cart. It can also keep information about the user and his preferences, and keep the
track of pending operations. Sessions are identified and tracked with a 120-bit SessionID,
which is passed from client to server and back as cookie or a modified URL. The SessionID is
globally unique and random. The session state object is created from the HttpSessionState
class, which defines a collection of session state items. The HttpSessionState class has the
following properties:

Properties
SessionID The unique session identifier
Itemname The value of the session state item with the specified name. This is the default
property of the HttpSessionState class.
Count The number of items in the session state collection.
TimeOut Gets and sets the amount of time, in minutes, allowed between requests before
the session-state provider terminates the session.

Methods:
Addname, value Adds an item to the session state collection.
Clear Removes all the items from session state collection.
Removename Removes the specified item from the session state collection.
RemoveAll Removes all keys and values from the session-state collection.
RemoveAt Deletes an item at a specified index from the session-state collection.

State Management:
State management is a preserve state control and object in an application because ASP.NET
web applications are stateless. A new instance of the Web page class is created each time the
page is posted to the server. If a user enters information into a web application, that
information would be lost in the round trip from the browser (MSDN).

In a single line, State management maintains and stores the information of any user till the end
of the user session.

Two types of State Management techniques are available in ASP.NET


1] Client Side:- View State, HiddenFields, Cookies
2] Server Side:- Session State, Application State

Hidden Fields
Hidden Fields are similar to a text box but does not get displayed on the UI. However you can
see the value of hidden fields when you view page source in the browser. Using Hidden Fields,
you can pass information from one page to another page without the end user's knowledge,
primarily for internal processing.
Drag and Drop a hiddenfield control on the web page from the Visual Studio toolbox and set its
value in the Page Load event as shown below -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
siteReference.Value = "https://www.google.com";
}
}
Run the page and check the source code. You will see the Hidden Field value as shown below –
<div>
<input type=”hidden” name=”siteReference” id=”siteReference”
value=”http://www.google.com”/>
<input type=”submit” name=”btnpageHitCounter” value=”Page Hit Counter”
Id=”btnPageHitCounter”/>
</div>

ViewState
ViewState is a important client side state management technique. ViewState is used to store
user data on page at the time of post back of web page.
ViewState does not hold the controls, it holds the values of controls. It does not restore the
value to control after page post back. ViewState can hold the value on single web page, if we go
to other page using response.redirect then ViewState will be null.
• ViewState stores data on single page
• ViewState is client side state management technique
• Session stores data on whole website pages
• Session is a server side state management technique
ViewState syntax same as Session, Session is a server side object while ViewState is a client
side object. Session can stores values across on multiple pages while ViewState stores values
on single page.

Viewstate Example
Store the value in viewstate
ViewState[“name”]=”Eagle Computers”;
Retrieve information from viewstate
string value=ViewState[“name”].ToString();

View State Example in ASP.Net


Open visual studio and design web form with two button control, a textbox and a label control
as shows in below figure.
Here, we have two button control one for a clear textbox value and second one for a retrieve
the same textbox value after clearing it. Before clearing textbox value store it in
ViewState[“name”] and after clearing it get value from ViewState[“name”] and display in
label while clicking display value button.

C# Code for above example


ViewState Example in ASP.Net
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnclear_Click(object sender, EventArgs e)
{
ViewState["name"] = txtname.Text;
txtname.Text = "";
}
protected void btndisplay_Click(object sender, EventArgs e)
{
lbl.Text = ViewState["name"].ToString();
}

Cookies
Cookies is a small pieces of text information which is stored on user hard drive using users
browser for identify users. It may contain username, ID, password or any information. Cookie
does not use server memory.
Cookies stored user computer at “C”\Document and Setting\Current login_User\Cookie”.
Types of Cookies
1. Persistence Cookie
2. Non-Persistence Cookie

1. Persistence Cookie
This type of cookies is permanently stored on user hard drive. Cookies which have an expiry
date time are called persistence cookies. These types of cookies stored user hard drive
permanently till the date time we set.
Example to create persistence cookie
Response.Cookies[“name”].Value = “Eagle Computers”;
Response.Cookies[“Eagle”].Expires = DateTime.Now.AddMinutes(10);

we can also create same cookies as like below


HttpCookie strname = new HttpCookie(“name”);
strname.Value = “Eagle Computers”;
strname.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Add(strname);
In above code we use Response.Cookies object for create Cookie.
In above example we have set 10 Minute time for Expire Cookie, we can retrieve cookie
values up to 10 minutes, after 10 minutes the cookies automatically expires.
2. Non-Persistence Cookie
This types of cookies are not permanently stored on user hard drive. It stores the information
up the user accesng the same browser. When user closes the browser the cookies will be
automatically deleted.
Example to create non-persistnce cookie
Response.Cookies[“name”].Value = “Eagle Computers”;

we can also create same non-persistence cookies as


HttpCookie strname = new HttpCookie(“name”);
strname.Value = “Eagle Computers”;
Response.Cookies.Add(strname);
Read Cookie Information
if (Request.Cookies[“name”] != null)
{
Label1.Text = Request.Cookies[“name”].Value;
}
ASP.Net Cookie Example
Open visual studio and design web form as shows below figure for create cookie and retrieve
cookie information.
C# code for Cookie Example
Create Cookie Button C# Code

protected void btncreate_Click(object sender, EventArgs e)


{
Response.Cookies["name"].Value = txtcreatecookie.Text;
Response.Cookies["name"].Expires = DateTime.Now.AddMinutes(1);
Label1.Text = "Cookie Created";
txtcreatecookie.Text = "";
}
Here, we create cookie with name parameter and assign textbox values to name cookie and
also set expiry time 1 minute. The cookie destroyed after 1 minute.
Retrieve Cookie Button Code

protected void btnretrieve_Click(object sender, EventArgs e)


{
if (Request.Cookies["name"] == null)
{
txtretrieve.Text = "No cookie found";
}
else
{
txtretrieve.Text = Request.Cookies["name"].Value;
}
}
On retrieve cookie button checks if cookie value not null then display cookie value in result, but
after 1 minute the cookie expires, after 1 minute cookie value will be null and result will be “No
cookie found”.

Server Side State Management


Unlike Client-side state management techniques, Server-side options are more secure but can
become slow to respond, depending on the information that is stored. Since these techniques
directly use the resources of the web server, scalability issues is something to be considered
when storing large amount of data.
ASP.NET provides some options to implement server-side state management:

Application State
ASP.Net Application state is a server side state management technique.
Application state is a global storage mechanism that used to stored data on the server and
shared for all users, means data stored in Application state is common for all user. Data from
Application state can be accessible anywhere in the application. Application state is based on
the System.Web.HttpApplicationState class.
The application state used same way as session state, but session state is specific for a single
user session, where as application state common for all users of asp.net application.
Syntax of Application State
Store information in application state
• Application[“name”] = “Eagle Computers”;
Retrieve information from application state
• string str = Application[“name”].ToString();
Example of Application State in ASP.Net
Generally we use application state for calculate how many times a given page has been visited
by various clients.
Design web page in visual studio as shows in below figure.

Here, we calculate total visit of uses visited web page by clicking “Click to Visit” button.
C# Code for Example
protected void btnvisit_Click(object sender, EventArgs e)
{
int count = 0;
if (Application["Visit"] != null)
{
count = Convert.ToInt32(Application["Visit"].ToString());
}
count = count + 1;
Application["Visit"] = count;
Label1.Text = "Total Visit = " + count.ToString();
}
Here, above output screen we use different browser for visit same page. The result counter
value stored in Application object so it would be changed simultaneously for both visitors.
In above case some time too many users click button at the same time, that time result wont be
accurate. This situation known as dead lock. To avoid dead lock we use Lock() and UnLock() in
application state.
Lock() and UnLock() in Application State
protected void btnvisit_Click(object sender, EventArgs e)
{
Application.Lock();
int cnt = 0;

if (Application["Visit"] != null)
{
cnt = Convert.ToInt32(Application["Visit"].ToString());
}
cnt = cnt + 1;
Application["Visit"] = cnt;

Application.UnLock();
Label1.Text = "Total Visit = " + cnt.ToString();

}
Session State
Session state is a period of time to visit a website for a particular user. Session can store the
client data on a server. Session is a best state management features to store the client data on
server separately for each user.
• Session can store value across on multiple pages of website.
• Viewstate can store value on single page.
In simple word we can say, At the same time more than one users login to system, all user
identification name store separately until they logout. session can store username or any
unique identification of user for a login period time.
Session value can be accessible from all pages from website. We can store some information in
session in one page and can access same information on rest of all page by using session.
• By default, Session state is enabled for all ASP.NET applications

When you login to any website with username and password. your username shows on all
other pages.The username will be stored in session and on page we access session value to
display username.
Syntax of session
Session[“session_name”] = “session value”;
Declare session in asp.net
Session[“name”]=”Eagle Computers”;
Response.Redirect(“nextpage.aspx”);
Above we create session with name parameter and assign value “Eagle Computers” to
session[“name”] and redirect user to other page “nextpage.aspx” using response.redirect
method.
Retrieve session value on other page
string myvalue= Session[“name”].ToString();
Response.Write(“Name = ” + myvalue);
Here, we retrieve session[“name”] value and store session value in string variable “myvalue”.
Session Example on ASP.Net C#
Here, we take example to understand session in asp.net c#. Open visual studio and design two
web page, one for assign value to session and other for retrieve value from session.
C# code for set session value on first page “default.aspx” on button click events. After
assigning a value to session we redirect to other page “next.aspx” using response.redirect
method. Here, we assign textbox name value to Session[“name”] and city value to
Session[“city”] and redirect to next.aspx page.
protected void btnsession_Click(object sender, EventArgs e)
{
Session["name"] = txtname.Text;
Session["city"] = txtcity.Text;
Response.Redirect("next.aspx");
}
On “next.aspx” page we retrieve and display session value on web page using label control. C#
code on “next.aspx” page for retrieve session value.

protected void btngetvalue_Click(object sender, EventArgs e)


{
lblname.Text = Session["name"].ToString();
lblcity.Text = Session["city"].ToString();
}
In above example we retrieve session value on next.aspx. you can retrieve session value all
pages of website until you clear session or abandon session.

Global.asax
The Global.asax file, also known as the ASP.NET application file, is an optional file that contains
code for responding to application-level events raised by ASP.NET or by HttpModules.
The Global.asax file resides in the root directory of an ASP.NET-based application. The
Global.asax file is parsed and dynamically compiled by ASP.NET.

The Global.asax file itself is configured so that any direct URL request for it is automatically
rejected; external users cannot download or view the code written within it.
The Global.asax file does not need recompilation if no changes have been made to it. There can
be only one Global.asax file per application and it should be located in the application's root
directory only.
The Global.asax contains two types of events those are

Events which are fired for every request

Application_BeginRequest() – This event raised at the start of every request for the web
application.

Application_AuthenticateRequest – This event rose just before the user credentials are
authenticated. We can specify our own authentication logic here to provide custom
authentication.
Application_AuthorizeRequest() – This event raised after successful completion of
authentication with user’s credentials. This event is used to determine user permissions. You
can use this method to give authorization rights to user.

Application_ResolveRequestCache() – This event raised after completion of an authorization


request and this event used in conjunction with output caching. With output caching, the
rendered HTML of a page is reused without executing its code.

Application_AcquireRequestState() – This event raised just before session-specific data is


retrieved for the client and is used to populate Session Collection for current request.

Application_PreRequestHandlerExecute() – This event called before the appropriate HTTP


handler executes the request.

Application_PostRequestHandlerExecute() – This event called just after the request is


handled by its appropriate HTTP handler.

Application_ReleaseRequestState() – This event raised when session specific information is


about to serialized from the session collection.

Application_UpdateRequestCache() – This event raised just before information is added to


output cache of the page.

Application_EndRequest() – This event raised at the end of each request right before the
objects released.

Events which are not fired for every request

Application_Start() – This event raised when the application starts up and application domain
is created.

Session_Start() – This event raised for each time a new session begins, This is a good place to
put code that is session-specific.

Application_Error() – This event raised whenever an unhandled exception occurs in the


application. This provides an opportunity to implement generic application-wide error
handling.

Session_End() – This event called when session of user ends.

Application_End() – This event raised just before when web application ends.
Application_Disposed() – This event fired after the web application is destroyed and this
event is used to reclaim the memory it occupies.

How to add global.asax file:

Select Website >>Add New Item (or Project >> Add New Item if you're using the Visual Studio
web project model) and choose the Global Application Class template.

After you have added the global.asax file, you will find that Visual Studio has added Application
Event handlers:

<%@ Application Language="C#" %>


<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>

Web.Config
A configuration file (web.config) is used to manage various settings that define a website. The
settings are stored in XML files that are separate from your application code. In this way you
can configure settings independently from your code. Generally a website contains a single
Web.config file stored inside the application root directory. However there can be many
configuration files that manage settings at various levels within an application.
Usage of configuration file

ASP.NET Configuration system is used to describe the properties and behaviors of various
aspects of ASP.NET applications. Configuration files help you to manage the many settings
related to your website. Each file is an XML file (with the extension .config) that contains a set
of configuration elements. Configuration information is stored in XML-based text files.

Benefits of XML-based Configuration files

• ASP.NET Configuration system is extensible and application specific information can be


stored and retrieved easily. It is human readable.
• You need not restart the web server when the settings are changed in configuration file.
ASP.NET automatically detects the changes and applies them to the running ASP.NET
application.
• You can use any standard text editor or XML parser to create and edit ASP.NET
configuration files.

What Web.config file contains?

There are number of important settings that can be stored in the configuration file. Some of the
most frequently used configurations, stored conveniently inside Web.config file are:

• Database connections
• Caching settings
• Session States
• Error Handling
• Security
Configuration file looks like this
1. <configuration>
2. <connectionStrings>
3. <add name="myCon" connectionString="server=MyServer;database=puran;uid=pu
ranmehra;pwd=mydata1223" />
4. </connectionStrings>
5. </configuration/>
Different types of Configuration files
• Machine.config - Server or machine-wide configuration file
• Web.config - Application configuration files which deal with a single application

Machine.config File
Configuration files are applied to an executing site based on a hierarchy. There is a global
configuration file for all sites in a given machine which is called Machine.config. This file is
typically found in the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG
directory.

The Machine.config file contains settings for all sites running on the machine provided another
.config further up the chain does not override any of these settings. Although Machine.config
provides a global configuration option, you can use .config files inside individual website
directories to provide more granular control. Between these two poles you can set a number of
other .config files with varying degree of applicable scope.
Application Configuration file (Web.config)
Each and Every ASP.NET application has its own copy of configuration settings stored in a file
called Web.config. If the web application spans multiple folders, each sub folder has its own
Web.config file that inherits or overrides the parent's file settings.

Processing of a Web.config file


When you initially run your web application, the runtime builds a cache of the configuration
settings for your web application by flattening the layer of configuration files as below,
1. The Machine.config file settings are retrieved.
2. The settings from the root Web.config files are added to the caches, overwriting any
conflicting settings that were earlier while reading the Machine.config file.
3. If there is a Web.config file at the root of the website, this file is read into the cache, all
overwriting any existing settings. The resulting cache contains the setting for this
website.
4. If you have subdirectories in your web application, each subdirectory can have a
Web.config file that includes settings that are specific to the files and folders that are
contained within the subdirectory. To calculate the effective setting for the folders, the
website settings are read (step 1-4) and then this Web.config file is read into cache for
this folder, overwriting (and thereby overriding) any existing settings.

You might also like