You are on page 1of 35

This topic outlines the application life cycle, listing important life-cycle events and describing how

code that you write can fit into the application life cycle. Within ASP.NET, several processing steps
must occur for an ASP.NET application to be initialized and process requests. Additionally, ASP.NET is
only one piece of the Web server architecture that services requests made by browsers. It is important
for you to understand the application life cycle so that you can write code at the appropriate life cycle
stage for the effect you intend.
Application Life Cycle in General
The following table describes the stages of the ASP.NET application life cycle.
Stage

Description

User requests an
application
resource from the
Web server.

The life cycle of an ASP.NET application starts with a request sent by a browser to
the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI
extension under the Web server. When a Web server receives a request, it
examines the file name extension of the requested file, determines which ISAPI
extension should handle the request, and then passes the request to the appropriate
ISAPI extension. ASP.NET handles file name extensions that have been mapped
to it, such as .aspx, .ascx, .ashx, and .asmx.
Note
If a file name extension has not been mapped to ASP.NET, then ASP.NET will
not receive the request. This is important to understand for applications that use
ASP.NET authentication. For example, because .htm files are typically not
mapped to ASP.NET, ASP.NET will not perform authentication or
authorization checks on requests for .htm files. Therefore, even if a file
contains only static content, if you want ASP.NET to check authentication,
create the file using a file name extension mapped to ASP.NET, such as .aspx.
Note
If you create a custom handler to service a particular file name extension, you
must map the extension to ASP.NET in IIS and also register the handler in your
application's Web.config file. For more information, see Introduction to HTTP
Handlers.

ASP.NET receives
the first request
for the
application.

When ASP.NET receives the first request for any resource in an application, a
class named ApplicationManager creates an application domain. Application
domains provide isolation between applications for global variables and allow
each application to be unloaded separately. Within an application domain, an
instance of the class named HostingEnvironment is created, which provides access
to information about the application such as the name of the folder where the
application is stored.
The following diagram illustrates this relationship:

ASP.NET also compiles the top-level items in the application if required,


including application code in the App_Code folder.
ASP.NET core
After the application domain has been created and the HostingEnvironment
objects are created object instantiated, ASP.NET creates and initializes core objects such as
for each request.
HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains
objects that are specific to the current application request, such as the
HttpRequest and HttpResponse objects. The HttpRequest object contains
information about the current request, including cookies and browser information.
The HttpResponse object contains the response that is sent to the client, including
all rendered output and cookies.
An
HttpApplication
object is assigned
to the request

After all core application objects have been initialized, the application is started
by creating an instance of the HttpApplication class. If the application has a
Global.asax file, ASP.NET instead creates an instance of the Global.asax class that
is derived from the HttpApplication class and uses the derived class to represent
the application.
Note
The first time an ASP.NET page or process is requested in an application, a
new instance of HttpApplication is created. However, to maximize
performance, HttpApplication instances might be reused for multiple
requests.
When an instance of HttpApplication is created, any configured modules are also
created. For instance, if the application is configured to do so, ASP.NET creates a
SessionStateModule module. After all configured modules are created, the
HttpApplication class's Init method is called.

The following diagram illustrates this relationship:

The request is
processed by the
HttpApplication
pipeline.

The following events are executed by the HttpApplication class while the request
is processed. The events are of particular interest to developers who want to
extend the HttpApplication class.
1.
Validate the request, which examines the information sent by the browser
and determines whether it contains potentially malicious markup. For more
information, see ValidateRequest and Script Exploits Overview.
2.
Perform URL mapping, if any URLs have been configured in the
UrlMappingsSection section of the Web.config file.
3.
Raise the BeginRequest event.
4.
Raise the AuthenticateRequest event.
5.
Raise the PostAuthenticateRequest event.
6.
Raise the AuthorizeRequest event.
7.
Raise the PostAuthorizeRequest event.
8.
Raise the ResolveRequestCache event.
9.
Raise the PostResolveRequestCache event.
10.
Based on the file name extension of the requested resource (mapped in the

11.
12.
13.
14.
15.

16.
17.
18.
19.
20.
21.
22.

application's configuration file), select a class that implements IHttpHandler


to process the request. If the request is for an object (page) derived from the
Page class and the page needs to be compiled, ASP.NET compiles the page
before creating an instance of it.
Raise the PostMapRequestHandler event.
Raise the AcquireRequestState event.
Raise the PostAcquireRequestState event.
Raise the PreRequestHandlerExecute event.
Call the ProcessRequest method (or the asynchronous version
BeginProcessRequest) of the appropriate IHttpHandler class for the request.
For example, if the request is for a page, the current page instance handles the
request.
Raise the PostRequestHandlerExecute event.
Raise the ReleaseRequestState event.
Raise the PostReleaseRequestState event.
Perform response filtering if the Filter property is defined.
Raise the UpdateRequestCache event.
Raise the PostUpdateRequestCache event.
Raise the EndRequest event.

Life Cycle Events and the Global.asax file


During the application life cycle, the application raises events that you can handle and calls particular
methods that you can override. To handle application events or methods, you can create a file named
Global.asax in the root directory of your application.
If you create a Global.asax file, ASP.NET compiles it into a class derived from the HttpApplication
class, and then uses the derived class to represent the application.
An instance of HttpApplication processes only one request at a time. This simplifies application event
handling because you do not need to lock non-static members in the application class when you access
them. This also allows you to store request-specific data in non-static members of the application class.
For example, you can define a property in the Global.asax file and assign it a request-specific value.
ASP.NET automatically binds application events to handlers in the Global.asax file using the naming
convention Application_event, such as Application_BeginRequest. This is similar to the way that
ASP.NET page methods are automatically bound to events, such as the page's Page_Load event. For
details, see ASP.NET Page Life Cycle Overview.
The Application_Start and Application_End methods are special methods that do not represent
HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for
each HttpApplication instance.
The following table lists some of the events and methods that are used during the application life cycle.
There are many more events than those listed, but they are not commonly used.
Event or method

Description

Application_Start

Called when the first resource (such as a page) in an ASP.NET application is

requested. The Application_Start method is called only one time during the
life cycle of an application. You can use this method to perform startup tasks
such as loading data into the cache and initializing static values.
You should set only static data during application start. Do not set any instance
data because it will be available only to the first instance of the
HttpApplication class that is created.
Application_event

Raised at the appropriate time in the application life cycle, as listed in the
application life cycle table earlier in this topic.
Application_Error can be raised at any phase in the application life cycle.
Application_EndRequest is the only event that is guaranteed to be raised in
every request, because a request can be short-circuited. For example, if two
modules handle the Application_BeginRequest event and the first one throws
an exception, the Application_BeginRequest event will not be called for the
second module. However, the Application_EndRequest method is always
called to allow the application to clean up resources.

HttpApplication.Init

Called once for every instance of the HttpApplication class after all modules
have been created.

Dispose

Called before the application instance is destroyed. You can use this method to
manually release any unmanaged resources. For more information, see Cleaning
Up Unmanaged Resources.

Application_End

Called once per lifetime of the application before the application is unloaded.

HTTP Modules
The ASP.NET application life cycle is extensible through IHttpModule classes. ASP.NET includes
several classes that implement IHttpModule, such as the SessionStateModule class. You can also
create your own classes that implement IHttpModule.
If you add modules to your application, the modules themselves can raise events. The application can
subscribe to in these events in the Global.asax file by using the convention modulename_eventname.
For example, to handle the Authenticate event raised by a FormsAuthenticationModule object, you can
create a handler named FormsAuthentication_Authenticate.
The SessionStateModule class is enabled by default in ASP.NET. All session events are automatically
wired up as Session_event, such as Session_Start. The Start event is raised each time a new session is
created. For more information, see Session State Overview.
Whats the sequence in which ASP.NET events are processed ?
1) Whats the sequence in which ASP.NET events are processed?
1) Initialize: Initialize settings needed during the lifetime of the incoming Web request.
2) Load view state: At the end of this phase, the ViewState property of a control is automatically
populated
3) Process postback data: Process incoming form data and update properties accordingly.
4) Load: Perform actions common to all requests, such as setting up a database query. At this point,
server controls in the tree are created and initialized, the state is restored, and form controls reflect

client-side data.
5) Send postback change notifications: Raise change events in response to state changes between the
current and previous postbacks.
6) Handle postback events: Handle the client-side event that caused the postback and raise appropriate
events on the server.
7) Prerender: Perform any updates before the output is rendered. Any changes made to the state of the
control in the prerender phase can be saved, while changes made in the rendering phase are lost.
8) Save state: The ViewState property of a control is automatically persisted to a string object after this
stage. This string object is sent to the client and back as a hidden variable. For improving efficiency, a
control can override the SaveViewState method to modify the ViewState property.
9 Render: Generate output to be rendered to the client.
10) Dispose: Perform any final cleanup before the control is torn down. References to expensive
resources such as database connections must be released in this phase.
11) Unload: Perform any final cleanup before the control is torn down. Control authors generally
perform cleanup in Dispose and do not handle this event.
Initialization, Page Load, PreRendor, Page unload
In which event are the controls fully loaded ?
Read Page Life cycle and write the answer here
ASP.NET Page Life Cycle Overview
When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of
processing steps. These include initialization, instantiating controls, restoring and maintaining state,
running event handler code, and rendering. It is important for you to understand the page life cycle so
that you can write code at the appropriate life-cycle stage for the effect you intend. Additionally, if you
develop custom controls, you must be familiar with the page life cycle in order to correctly initialize
controls, populate control properties with view-state data, and run any control behavior code. (The life
cycle of a control is based on the page life cycle, but the page raises more events for a control than are
available for an ASP.NET page alone.)
General Page Life-cycle Stages
In general terms, the page goes through the stages outlined in the following table. In addition to the
page life-cycle stages, there are application stages that occur before and after a request but are not
specific to a page. For more information, see ASP.NET Application Life Cycle Overview.
Stage

Description

Page request

The page request occurs before the page life cycle begins. When the page is requested
by a user, ASP.NET determines whether the page needs to be parsed and compiled
(therefore beginning the life of a page), or whether a cached version of the page can be
sent in response without running the page.
(Query: When a page requires compilation?)

Start

In the start step, page properties such as Request and Response are set. At this stage, the
page also determines whether the request is a postback or a new request and sets the
IsPostBack property. Additionally, during the start step, the page's UICulture property is
set.

Page
initialization

During page initialization, controls on the page are available and each control's
UniqueID property is set. Any themes are also applied to the page. If the current request
is a postback, the postback data has not yet been loaded and control property values
have not been restored to the values from view state.

Load

During load, if the current request is a postback, control properties are loaded with
information recovered from view state and control state.
Query: If not postback then what happens?

Validation

During validation, the Validate method of all validator controls is called, which sets the
IsValid property of individual validator controls and of the page.
(Query: Why you require validate the control?)

Postback event If the request is a postback, any event handlers are called.
handling
Rendering

Before rendering, view state is saved for the page and all controls. During the rendering
phase, the page calls the Render method for each control, providing a text writer that
writes its output to the OutputStream of the page's Response property.

Unload

Unload is called after the page has been fully rendered, sent to the client, and is ready to
be discarded. At this point, page properties such as Response and Request are unloaded
and any cleanup is performed.

Life-cycle Events
Within each stage of the life cycle of a page, the page raises events that you can handle to run your own
code. For control events, you bind the event handler to the event, either declaratively using attributes
such as onclick, or in code.
Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular
names and automatically runs those methods when certain events are raised. If the AutoEventWireup
attribute of the @ Page directive is set to true (or if it is not defined, since by default it is true), page
events are automatically bound to methods that use the naming convention of Page_event, such as
Page_Load and Page_Init. For more information on automatic event wire-up, see ASP.NET Web
Server Control Event Model.
The following table lists the page life-cycle events that you will use most frequently. There are more
events than those listed; however, they are not used for most page processing scenarios. Instead, they
are primarily used by server controls on the ASP.NET Web page to initialize and render themselves. If
you want to write your own ASP.NET server controls, you need to understand more about these stages.
For information about creating custom controls, see Developing Custom ASP.NET Server Controls.

Page Event
PreInit

Typical Use
Use this event for the following:
Check the IsPostBack property to determine whether this is the first time

the page is being processed.

Create or re-create dynamic controls.

Set a master page dynamically.

Set the Theme property dynamically.

Read or set profile property values.


Note
If the request is a postback, the values of the controls have not yet been restored
from view state. If you set a control property at this stage, its value might be
overwritten in the next event.

Init

Raised after all controls have been initialized and any skin settings have been
applied. Use this event to read or initialize control properties.

InitComplete

Raised by the Page object. Use this event for processing tasks that require all
initialization be complete.

PreLoad

Use this event if you need to perform processing on your page or control before the
Load event.
After the Page raises this event, it loads view state for itself and all controls, and
then processes any postback data included with the Request instance.

Load

The Page calls the OnLoad event method on the Page, then recursively does the
same for each child control, which does the same for each of its child controls until
the page and all controls are loaded.
Use the OnLoad event method to set properties in controls and establish database
connections.

Control events

Use these events to handle specific control events, such as a Button control's Click
event or a TextBox control's TextChanged event.
Note
In a postback request, if the page contains validator controls, check the IsValid
property of the Page and of individual validation controls before performing any
processing.

LoadComplete
PreRender

Use this event for tasks that require that all other controls on the page be loaded.
Before this event occurs:
The Page object calls EnsureChildControls for each control and for the

page.

Each data bound control whose DataSourceID property is set calls its
DataBind method. For more information, see Data Binding Events for DataBound Controls below.

The PreRender event occurs for each control on the page. Use the event to make
final changes to the contents of the page or its controls.
SaveStateComplete Before this event occurs, ViewState has been saved for the page and for all controls.
Any changes to the page or controls at this point will be ignored.
Use this event perform tasks that require view state to be saved, but that do not
make any changes to controls.
Render

This is not an event; instead, at this stage of processing, the Page object calls this
method on each control. All ASP.NET Web server controls have a Render method
that writes out the control's markup that is sent to the browser.
If you create a custom control, you typically override this method to output the
control's markup. However, if your custom control incorporates only standard
ASP.NET Web server controls and no custom markup, you do not need to override
the Render method. For more information, see Developing Custom ASP.NET
Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not
need to explicitly render the control in code.

Unload

This event occurs for each control and then for the page. In controls, use this event
to do final cleanup for specific controls, such as closing control-specific database
connections.
For the page itself, use this event to do final cleanup work, such as closing open files
and database connections, or finishing up logging or other request-specific tasks.
Note
During the unload stage, the page and its controls have been rendered, so you
cannot make further changes to the response stream. If you attempt to call a
method such as the Response.Write method, the page will throw an exception.

Additional Page Life Cycle Considerations


Individual ASP.NET server controls have their own life cycle that is similar to the page life cycle. For
example, a control's Init and Load events occur during the corresponding page events.
Although both Init and Load recursively occur on each control, they happen in reverse order. The Init
event (and also the Unload event) for each child control occur before the corresponding event is raised
for its container (bottom-up). However the Load event for a container occurs before the Load events
for its child controls (top-down).

You can customize the appearance or content of a control by handling the events for the control, such as
the Click event for the Button control and the SelectedIndexChanged event for the ListBox control.
Under some circumstances, you might also handle a control's DataBinding or DataBound events. For
more information, see the class reference topics for individual controls and Developing Custom
ASP.NET Server Controls.
When inheriting a class from the Page class, in addition to handling events raised by the page, you can
override methods from the page's base class. For example, you can override the page's InitializeCulture
method to dynamically set culture information. Note that when creating an event handler using the
Page_event syntax, the base implementation is implicitly called and therefore you do not need to call it
in your method. For example, the base page class's OnLoad method is always called, whether you
create a Page_Load method or not. However, if you override the page OnLoad method with the
override keyword (Overrides in Visual Basic), you must explicitly call the base method. For example,
if you override the OnLoad method on the page, you must call base.Load (MyBase.Load in Visual
Basic) in order for the base implementation to be run.
Catch-up Events for Added Controls
If controls are created dynamically at run time or are authored declaratively within templates of databound controls, their events are initially not synchronized with those of other controls on the page. For
example, for a control that is added at run time, the Init and Load events might occur much later in the
page life cycle than the same events for controls created declaratively. Therefore, from the time that
they are instantiated, dynamically added controls and controls in templates raise their events one after
the other until they have caught up to the event during which it was added to the Controls collection.
In general, you do not need to be concerned about this unless you have nested data-bound controls. If a
child control has been data bound, but its container control has not yet been data bound, the data in the
child control and the data in its container control can be out of sync. This is true particularly if the data
in the child control performs processing based on a data-bound value in the container control.
For example, suppose you have a GridView that displays a company record in each row along with a
list of the company officers in a ListBox control. To fill the list of officers, you would bind the ListBox
control to a data source control (such as SqlDataSource) that retrieves the company officer data using
the CompanyID in a query.
If the ListBox control's data-binding properties, such as DataSourceID and DataMember, are set
declaratively, the ListBox control will try to bind to its data source during the containing row's
DataBinding event. However, the CompanyID field of the row does not contain a value until the
GridView control's RowDataBound event occurs. In this case, the child control (the ListBox control) is

10

bound before the containing control (the GridView control) is bound, so their data-binding stages are
out of sync.
To avoid this condition, put the data source control for the ListBox control in the same template item as
the ListBox control itself, and do not set the data binding properties of the ListBox declaratively.
Instead, set them programmatically at run time during the RowDataBound event, so that the ListBox
control does not bind to its data until the CompanyID information is available.
For more information, see Binding to Data Using a Data Source Control.
Data Binding Events for Data-Bound Controls
To help you understand the relationship between the page life cycle and data binding events, the
following table lists data-related events in data-bound controls such as the GridView, DetailsView, and
FormView controls.
Control Event

Typical Use

DataBinding

This event is raised by data-bound controls before the


PreRender event of the containing control (or of the Page
object) and marks the beginning of binding the control to the
data.
Use this event to manually open database connections, if
required. (The data source controls often make this
unnecessary.)

RowCreated (GridView only) or


ItemCreated (DataList, DetailsView,
SiteMapPath, DataGrid, FormView, and
Repeater controls)

Use this event to manipulate content that is not dependent on


data binding. For example, at run time, you might
programmatically add formatting to a header or footer row in
a GridView control.

RowDataBound (GridView only) or


ItemDataBound (DataList,
SiteMapPath, DataGrid, and Repeater
controls)

When this event occurs, data is available in the row or item,


so you can format data or set the FilterExpression property on
child data source controls for displaying related data within
the row or item.

DataBound

This event marks the end of data-binding operations in a databound control. In a GridView control, data binding is
complete for all rows and any child controls.
Use this event to format data bound content or to initiate data
binding in other controls that depend on values from the
current control's content. (For details, see "Catch-up Events
for Added Controls" earlier in this topic.)

Login Control Events

11

The Login control can use settings in the Web.config file to manage membership authentication
automatically. However, if your application requires you to customize how the control works, or if you
want to understand how Login control events relate to the page life cycle, you can use the events listed
in the following table.
Control
Event
LoggingIn

Typical Use
This event is raised during a postback, after the page's LoadComplete event has
occurred. It marks the beginning of the login process.
Use this event for tasks that must occur prior to beginning the authentication process.

Authenticate This event is raised after the LoggingIn event.


Use this event to override or enhance the default authentication behavior of a Login
control.
LoggedIn

This event is raised after the user name and password have been authenticated.
Use this event to redirect to another page or to dynamically set the text in the control.
This event does not occur if there is an error or if authentication fails.

LoginError

This event is raised if authentication was not successful.


Use this event to set text in the control that explains the problem or to direct the user to a
different page.

How can we identify that the Page is PostBack ?


When an event is triggered, for instance, a button is clicked, or an item in a grid
is selected, the page is submitted back to the server for processing, along with
information about the event and any preexisting data on the page (via view state).
We say the page posts back to the server. This is a powerful concept to grasp
because it is postback that lets us run code on the server rather than on the clients
browser, and it is postback that lets our server code know which items within a
drop-down list were selected, or what information a user typed into a text box.
But what would happen if you had multiple DropDownList controls that were
populated with database data? Users could interact with those DropDownList
controls and, in turn, we could set certain options within the page based on what
they selected from the drop-down menus. Although this seems like a common
task, with traditional ASP it incurred considerable overhead. The problem is that
while the data thats bound to the drop-down menu from the database never
changes, every time the user selects an item from the drop-down menu and a
postback has to be done, the database must be accessed again to rebuild the
contents of each drop-down list on the page. However, this is not a problem in
ASP.NET.
In ASP.NET we can check for postback with the IsPostBack property, and thus
avoid performing any time consuming tasks unnecessarily. IsPostBack is a pagelevel
propertymeaning
that
its a
property of
the
page
itselfand wed
most
commonly use it in the Page_Load() event handler to execute code only when
the page is first loaded.

12

How does ASP.NET maintain state in between subsequent request ?


A new instance of the Web page class is created each time the page is posted to the server. In traditional
Web programming, this would typically mean that all information associated with the page and the
controls on the page would be lost with each round trip. For example, if a user enters information into a
text box, that information would be lost in the round trip from the browser or client device to the server.
To overcome this inherent limitation of traditional Web programming, ASP.NET includes several
options that help you preserve data on both a per-page basis and an application-wide basis. These
features are as follows:

View state

Control state

Hidden fields

Cookies

Query strings

Application state

Session state

Profile Properties
View state, control state, hidden fields, cookies, and query strings all involve storing data on the client
in various ways. However, application state, session state, and profile properties all store data in
memory on the server. Each option has distinct advantages and disadvantages, depending on the
scenario.
Client-Based State Management Options
The following sections describe options for state management that involve storing information either in
the page or on the client computer. For these options, no information is maintained on the server
between round trips.
View State
The ViewState property provides a dictionary object for retaining values between multiple requests for
the same page. This is the default method that the page uses to preserve page and control property
values between round trips.
When the page is processed, the current state of the page and controls is hashed into a string and saved
in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState
property exceeds the specified value in the MaxPageStateFieldLength property. When the page is
posted back to the server, the page parses the view-state string at page initialization and restores
property information in the page.
You can store values in view state as well. For details, see How to: Save Values in View State. For
recommendations about when you should use view state, see ASP.NET State Management
Recommendations.
Control State
Sometimes you need to store control-state data in order for a control to work properly. For example, if
you have written a custom control that has different tabs that show different information, in order for
that control to work as expected, the control needs to know which tab is selected between round trips.

13

The ViewState property can be used for this purpose, but view state can be turned off at a page level by
developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a
feature in ASP.NET called control state.
The ControlState property allows you to persist property information that is specific to a control and
cannot be turned off like the ViewState property.
Hidden Fields
ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML
hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as
you can with a standard control. When a page is submitted to the server, the content of a hidden field is
sent in the HTTP form collection along with the values of other controls. A hidden field acts as a
repository for any page-specific information that you want to store directly in the page.
Security Note
It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any
information in a hidden field that is sensitive or that your application relies on to work properly. For
more information, see ASP.NET State Management Recommendations.
A HiddenField control stores a single variable in its Value property and must be explicitly added to the
page. For more information, see HiddenField Web Server Control Overview.
In order for hidden-field values to be available during page processing, you must submit the page using
an HTTP POST command. If you use hidden fields and a page is processed in response to a link or an
HTTP GET command, the hidden fields will not be available. For usage recommendations, see
ASP.NET State Management Recommendations.
Cookies
A cookie is a small amount of data that is stored either in a text file on the client file system or inmemory in the client browser session. It contains site-specific information that the server sends to the
client along with page output. Cookies can be temporary (with specific expiration times and dates) or
persistent.
You can use cookies to store information about a particular client, session, or application. The cookies
are saved on the client device, and when the browser requests a page, the client sends the information in
the cookie along with the request information. The server can read the cookie and extract its value. A
typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated
in your application.
Security Note
The browser can only send the data back to the server that originally created the cookie. However,
malicious users have ways to access cookies and read their contents. It is recommended that you do
not store sensitive information, such as a user name or password, in a cookie. Instead, store a token in
the cookie that identifies the user, and then use the token to look up the sensitive information on the
server.
For more information about using cookies, see Cookies and ASP.NET State Management
Recommendations.

14

Query Strings
A query string is information that is appended to the end of a page URL. A typical query string might
look like the following example:
Copy Code
http://www.contoso.com/listwidgets.aspx?category=basic&price=100
In the URL path above, the query string starts with a question mark (?) and includes two attribute/value
pairs, one called "category" and the other called "price."
Query strings provide a simple but limited way to maintain state information. For example, they are an
easy way to pass information from one page to another, such as passing a product number from one
page to another page where it will be processed. However, some browsers and client devices impose a
2083-character limit on the length of the URL.
Security Note
Information that is passed in a query string can be tampered with by a malicious user. Do not rely on
query strings to convey important or sensitive data. Additionally, a user can bookmark the URL or
send the URL to other users, thereby passing that information along with it. For more information, see
ASP.NET State Management Recommendations and How to: Protect Against Script Exploits in a Web
Application by Applying HTML Encoding to Strings.
In order for query string values to be available during page processing, you must submit the page using
an HTTP GET command. That is, you cannot take advantage of a query string if a page is processed in
response to an HTTP POST command. For usage recommendations, see ASP.NET State Management
Recommendations.
Server-Based State Management Options
ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting
information on the client. With server-based state management, you can decrease the amount of
information sent to the client in order to preserve state, however it can use costly resources on the
server. The following sections describe three server-based state management features: application state,
session state, and profile properties.
Application State
ASP.NET allows you to save values using application state which is an instance of the
HttpApplicationState class for each active Web application. Application state is a global storage
mechanism that is accessible from all pages in the Web application. Thus, application state is useful for
storing information that needs to be maintained between server round trips and between requests for
pages. For more information, see ASP.NET Application State Overview.
Application state is stored in a key/value dictionary that is created during each request to a specific
URL. You can add your application-specific information to this structure to store it between page
requests.
Once you add your application-specific information to application state, the server manages it. For
usage recommendations, see ASP.NET State Management Recommendations.

15

Session State
ASP.NET allows you to save values by using session state which is an instance of the
HttpSessionState class for each active Web-application session. For an overview, see Session State
Overview.
Session state is similar to application state, except that it is scoped to the current browser session. If
different users are using your application, each user session will have a different session state. In
addition, if a user leaves your application and then returns later, the second user session will have a
different session state from the first.
Session state is structured as a key/value dictionary for storing session-specific information that needs
to be maintained between server round trips and between requests for pages. For more information, see
Session State Overview.
You can use session state to accomplish the following tasks:

Uniquely identify browser or client-device requests and map them to an individual session
instance on the server.

Store session-specific data on the server for use across multiple browser or client-device
requests within the same session.

Raise appropriate session management events. In addition, you can write application code
leveraging these events.
Once you add your application-specific information to session state, the server manages this object.
Depending on which options you specify, session information can be stored in cookies, on an out-ofprocess server, or on a computer running Microsoft SQL Server. For usage recommendations, see
ASP.NET State Management Recommendations.
Profile Properties
ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This
feature is similar to session state, except that the profile data is not lost when a user's session expires.
The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and
associated with an individual user. The ASP.NET profile allows you to easily manage user information
without requiring you to create and maintain your own database. In addition, the profile makes the user
information available using a strongly typed API that you can access from anywhere in your
application. You can store objects of any type in the profile. The ASP.NET profile feature provides a
generic storage system that allows you to define and maintain almost any kind of data while still
making the data available in a type-safe manner.
To use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider
class that allows you to store profile data in a SQL database, but you can also create your own profile
provider class that stores profile data in a custom format and to a custom storage mechanism such as an
XML file, or even to a web service.
Because data that is placed in profile properties is not stored in application memory, it is preserved
through Internet Information Services (IIS) restarts and worker-process restarts without losing data.
Additionally, profile properties can be persisted across multiple processes such as in a Web farm or a
Web garden. For more information, see ASP.NET Profile Properties Overview.
What is event bubbling ?

16

Event Bubbling is nothing but events raised by child controls is handled by the parent control. Example:
Suppose consider datagrid as parent control in which there are several child controls.There can be a
column of link buttons right.Each link button has click event.Instead of writing event routine for each
link button write one routine for parent which will handlde the click events of the child link button
events.Parent can know which child actaully triggered the event.That thru arguments passed to event
routine. " Happy programming"
Bubbling an Event
The ASP.NET page framework provides a technique called event bubbling that allows a child control to
propagate events up its containment hierarchy. Event bubbling enables events to be raised from a more
convenient location in the controls hierarchy and allows event handlers to be attached to the original
control as well as to the control that exposes the bubbled event.
Event bubbling is used by the data-bound controls (Repeater, DataList, and DataGrid) to expose
command events raised by child controls (within item templates) as top-level events. While ASP.NET
server controls in the .NET Framework use event bubbling for command events (events whose event
data class derives from CommandEventArgs), any event defined on a server control can be bubbled.
A control can participate in event bubbling through two methods that it inherits from the base class
System.Web.UI.Control. These methods are OnBubbleEvent and RaiseBubbleEvent. The following
code shows the signatures of these methods.
[C#]
Copy Code
protected virtual bool OnBubbleEvent( object source, EventArgs args ); protected void
RaiseBubbleEvent( object source, EventArgs args ); [Visual Basic] Overridable Protected Function
OnBubbleEvent( _ ByVal source As Object, _ ByVal args As EventArgs _ ) As Boolean Protected Sub
RaiseBubbleEvent( _ ByVal source As Object, _ ByVal args As EventArgs _ )
The implementation of RaiseBubbleEvent is provided by Control and cannot be overridden.
RaiseBubbleEvent sends the event data up the hierarchy to the control's parent. To handle or to raise
the bubbled event, a control must override the OnBubbleEvent method.
A control that has an event bubbled to it does one of the following three things.

It does nothing, in which case the event is automatically bubbled up to its parent.

It does some processing and continues to bubble the event. To accomplish this, a control must
override OnBubbleEvent and invoke RaiseBubbleEvent from OnBubbleEvent. The
following code fragment (from the Templated Data-Bound Control Sample) bubbles an event
after checking for the type of the event arguments.

17

[C#]
Copy Code
protected override bool OnBubbleEvent(object source, EventArgs e) { if (e is
CommandEventArgs) { // Adds information about an Item to the // CommandEvent.
TemplatedListCommandEventArgs args = new TemplatedListCommandEventArgs(this,
source, (CommandEventArgs)e); RaiseBubbleEvent(this, args); return true; } return false; }
[Visual Basic] Protected Overrides Function OnBubbleEvent(source As Object, e As
EventArgs) As Boolean If TypeOf e Is CommandEventArgs Then ' Adds information about
an Item to the ' CommandEvent. Dim args As New TemplatedListCommandEventArgs(Me,
source, CType(e, CommandEventArgs)) RaiseBubbleEvent(Me, args) Return True End If
Return False End Function

It stops bubbling the event and raises and/or handles the event. Raising an event involves
invoking the method that dispatches the event to listeners. To raise the bubbled event, a
control must override OnBubbleEvent to invoke the OnEventName method that raises the
bubbled event. A control that raises a bubbled event generally exposes the bubbled event as a
top-level event. The following code fragment (from the Templated Data-Bound Control
Sample) raises a bubbled event.
[C#]
Copy Code
protected override bool OnBubbleEvent(object source, EventArgs e) { bool handled = false;
if (e is TemplatedListCommandEventArgs) { TemplatedListCommandEventArgs ce =
(TemplatedListCommandEventArgs)e; OnItemCommand(ce); handled = true; } return
handled; } [Visual Basic] Protected Overrides Function OnBubbleEvent(source As Object, e
As EventArgs) As Boolean Dim handled As Boolean = False If TypeOf e Is
TemplatedListCommandEventArgs Then Dim ce As TemplatedListCommandEventArgs =
CType(e, TemplatedListCommandEventArgs) OnItemCommand(ce) handled = True End If
Return handled End Function

For samples that demonstrate event bubbling, see Event Bubbling Control Sample and Templated DataBound Control Sample.
Note While the method that enables event bubbling, OnBubbleEvent, follows the standard .NET
Framework naming pattern for methods that raise events, there is no event named BubbleEvent. The
bubbled event is exposed as a top-level event in the control that stops event bubbling. For example, the

18

DataList control exposes Command events from controls in its template as ItemCommand events.
Note also that the standard signature of OnEventName methods in the .NET Framework has one
argument (protected void OnEventName (EventArgs e)). However, OnBubbleEvent has two
arguments because the event originates outside the control; the second argument supplies the source.
The discussion so far shows how a control can respond to an event that is bubbled up to it. The
following section shows how to author a control that defines a bubbled event.
Defining a Bubbled Event
If you want your control to enable event bubbling for an event that it defines, it must invoke the
RaiseBubbleEvent from the OnEventName method that raises the event. No additional work needs to
be done from within the control. The following code fragment shows a control that defines a
Command event that enables bubbling.
[C#]
Copy Code
protected virtual void OnCommand(CommandEventArgs e) { CommandEventHandler handler =
(CommandEventHandler)Events[EventCommand]; if (handler != null) handler(this,e); // The
Command event is bubbled up the control hierarchy. RaiseBubbleEvent(this, e); } [Visual Basic]
Protected Overridable Sub OnCommand(e As CommandEventArgs) Dim handler As
CommandEventHandler = CType(Events(EventCommand), CommandEventHandler) If Not (handler
Is Nothing) Then handler(Me, e) End If ' The Command event is bubbled up the control hierarchy.
RaiseBubbleEvent(Me, e) End Sub
Note Event bubbling is not limited to command events. You can use the mechanism described here to
bubble any event.

How do we assign page specific attributes ?


@ Page
Defines page-specific (.aspx file) attributes used by the ASP.NET page parser and compiler.
<%@ Page attribute="value" [attribute="value"...] %>
Attributes
AspCompat
When set to true, this allows the page to be executed on a single-threaded apartment
(STA) thread. This allows the page to call STA components, such as a component
developed with Microsoft Visual Basic 6.0. Setting this attribute to true also allows the
page to call COM+ 1.0 components that require access to unmanaged Active Server

19

Pages (ASP) built-in objects. These are accessible through the ObjectContext object or
the OnStartPage method. The default is false.
Note Setting this attribute to true can cause your page's performance to degrade. For
more information, see the Remarks section.
AutoEventWireup
Indicates whether the page's events are autowired. true if event autowiring is enabled;
otherwise, false. The default is true. For more information, see Web Server Control
Event Model.
Buffer
Determines whether HTTP response buffering is enabled. true if page buffering is
enabled; otherwise, false. The default is true.
ClassName
Specifies the class name for the page that will be dynamically compiled automatically
when the page is requested. This value can be any valid class name but should not
include a namespace.
ClientTarget
Indicates the target user agent for which ASP.NET server controls should render
content. This value can be any valid user agent or alias.
CodeBehind
Specifies the name of the compiled file that contains the class associated with the page.
This attribute is used by the Visual Studio .NET Web Forms designer. It tells the
designer where to find the page class so that the designer can create an instance of it for
you to work with at design time. For example, if you create a Web Forms page in Visual
Studio called WebForm1, the designer will assign the Codebehind attribute the value
of WebForm1.aspx.vb, for Visual Basic, or WebForm1.aspx.cs, for C#. This attribute is
not used at run time.
CodePage
Indicates the code page value for the response.
Note If you created your Web Forms page using a code page other than the default
code page of the Web server on which the page will run, you must set this attribute. The
value you enter should be the code page for the computer on which you created the
page. For more information about code pages, search the Microsoft Developers
Network (MSDN) at http://msdn.microsoft.com.

20

CompilerOptions
A string containing compiler options used to compile the page. In C# and Visual
Basic .NET, this is a sequence of compiler command-line switches.
ContentType
Defines the HTTP content type of the response as a standard MIME type. Supports any
valid HTTP content-type string. For a list of possible values, search for MIME in
MSDN at http://www.microsoft.com/technet.
Culture
Indicates the culture setting for the page. For information about culture settings and
possible culture values, see the CultureInfo class.
Debug
Indicates whether the page should be compiled with debug symbols. true if the page
should be compiled with debug symbols; otherwise, false.
Description
Provides a text description of the page. This value is ignored by the ASP.NET parser.
EnableSessionState
Defines session-state requirements for the page. true if session state is enabled;
ReadOnly if session state can be read but not changed; otherwise, false. The default is
true. These values are case-insensitive. For more information, see Session State.
EnableViewState
Indicates whether view state is maintained across page requests. true if view state is
maintained; otherwise, false. The default is true.
EnableViewStateMac
Indicates that ASP.NET should run a machine authentication check (MAC) on the
page's view state when the page is posted back from the client. true if view state should
be MAC checked; otherwise, false. The default is false.
Note A view-state MAC is an encrypted version of the hidden variable that a page's
view state is persisted to when sent to the browser. When you set this attribute to true,
the encrypted view state is checked to verify that it has not been tampered with on the
client.
ErrorPage
Defines a target URL for redirection if an unhandled page exception occurs.
Explicit

21

Determines whether the page is compiled using the Visual Basic Option Explicit mode.
true indicates that the Visual Basic explicit compile option is enabled and that all
variables must be declared using a Dim, Private, Public, or ReDim statement;
otherwise, false. The default is false.
Note This attribute is ignored by languages other than Visual Basic .NET. Also, this
option is set to true in the Machine.config configuration file. For more information, see
Machine Configuration Files.
Inherits
Defines a code-behind class for the page to inherit. This can be any class derived from
the Page class. For information about code-behind classes, see Web Forms Code
Model.
Language
Specifies the language used when compiling all inline rendering (<% %> and <%=
%>) and code declaration blocks within the page. Values can represent any .NETsupported language, including Visual Basic, C#, or JScript .NET.
LCID
Defines the locale identifier for the Web Forms page.
Note The locale identifier is a 32-bit value that uniquely defines a locale. ASP.NET
uses the default locale of the Web server unless you specify a different locale for a Web
Forms page by using this attribute. For more information about locales, search MSDN
at http://msdn.microsoft.com.
ResponseEncoding
Indicates the response encoding of page content. Supports values from the
Encoding.GetEncoding method.
Src
Specifies the source file name of the code-behind class to dynamically compile when
the page is requested. You can choose to include programming logic for your page
either in a code-behind class or in a code declaration block in the .aspx file.
Note RAD designers, such as Visual Studio .NET, do not use this attribute. Instead,
they precompile code-behind classes and then use the Inherits attribute.
SmartNavigation
Indicates whether the page supports the smart navigation feature of Internet Explorer
5.5 or later..

22

Note For more information about smart navigation, see the Remarks section.
Strict
Indicates that the page should be compiled using the Visual Basic Option Strict mode.
true if Option Strict is enabled; otherwise, false. The default is false.
Note This attribute is ignored by languages other than Visual Basic .NET.
Trace
Indicates whether tracing is enabled. true if tracing is enabled; otherwise, false. The
default is false. For more information, see ASP.NET Trace.
TraceMode
Indicates how traces messages are to be displayed for the page when tracing is enabled.
Possible values are SortByTime and SortByCategory. The default, when tracing is
enabled, is SortByTime. For more information about tracing, see ASP.NET Trace.
Transaction
Indicates whether transactions are supported on the page. Possible values are Disabled,
NotSupported, Supported, Required, and RequiresNew. The default is Disabled.
UICulture
Specifies the UI culture setting to use for the page. Supports any valid UI culture value.
ValidateRequest
Indicates whether request validation should occur. If true, request validation checks all
input data against a hard-coded list of potentially dangerous values. If a match occurs,
an HttpRequestValidationException Class is thrown. The default is true.
This feature is enabled in the machine configuration file (Machine.config). You can
disable it in your application configuration file (Web.config) or on the page by setting
this attribute to false.
Note This functionality helps reduce the risk of cross-site scripting attacks for
straightforward pages and ASP.NET applications. An application that does not properly
validate user input can suffer from many types of malformed input attacks, including
cross-site scripting and SQL Server injection attacks. There is no substitute for carefully
evaluating all forms of input in an application and making sure that they are either
properly validated or encoded, or that the application is escaped prior to manipulating
data or sending information back to the client. For more information about cross-site
scripting, see http://www.cert.org/advisories/CA-2000-02.html.
WarningLevel

23

Indicates the compiler warning level at which you want the compiler to abort
compilation for the page. Possible values are 0 through 4. For more information, see the
CompilerParameters.WarningLevel Property property.
Remarks
This directive can be used only in Web Forms pages. You can include only one @ Page
directive per .aspx file. To define multiple attributes for the directive, use a space-separated list
(do not include a space on either side of the equal sign of a specific attribute, as in
trace="true").
Smart navigation is an ASP.NET feature that is supported in Internet Explorer 5.5 and later
browsers. It allows a page to be refreshed while maintaining scroll position and element focus
between navigations, causing only a single page to be stored in the browser's history, and
without the common flicker associated with refreshing a Web page. Smart navigation is best
used with ASP.NET pages that require frequent postbacks but with visual content that does not
change dramatically on return. Consider this carefully when deciding whether to set this
attribute to true.
When the AspCompat attribute is set to true for a page, if you use a constructor to create a
COM component before the request is scheduled, it will run on a multithreaded apartment
(MTA) thread. Doing this causes significant Web server performance degradation. To avoid
this problem, create COM components only from within one of the Page events (such as
Page_Load, Page_Init, and so on) or one of the Page methods. Be sure as well that the objects
are not created at page construction time. The following examples demonstrate the incorrect
and correct way to instantiate a COM object in an AspCompat page. MyComObject is the
component, and comObj is the instance of the component.
[C#]
Copy Code
<%@ Page AspCompat="TRUE" language="C#" %> <script runat="server" > // Avoid this
when using AspCompat. MyComObject comObj = new MyComObject(); public void
Page_Load() { // comObj.DoSomething() } </script> [Visual Basic] <%@ Page
ASPCOMPAT="TRUE" language="VB" %> <script runat="server" > ' Avoid this when using
AspCompat. Dim comObj As MyComObject = New MyComObject() Public Sub
Page_Load() ' comObj.DoSomething() End Sub </script>

24

The recommended way to instantiate a COM object in a page with AspCompat enabled.
[C#]
Copy Code
<%@ Page AspCompat="true" language="C#" %> <script runat="server" > MyComObject
comObj; public void Page_Load(){ // Use comObj here when the code is running on the STA
thread pool. comObj = New MyComObject(); // comObj.DoSomething(); } [Visual Basic] <
%@ Page AspCompat ="true" language="VB" %> <script runat="server" > Dim comObj As
MyComObject Public Sub Page_Load() comObj = New MyComObject() '
comObj.DoSomething() End Sub </script>
Example
The following code instructs the ASP.NET page compiler to use Visual Basic as the inline code
language and sets the default HTTP MIME ContentType transmitted to the client to
"text/xml".
Copy Code
<%@ Page Language="VB" ContentType="text/xml" %>

Administrator wants to make a security check that no one has


tampered with ViewState
, how can he ensure this ?

Securing View State


The ViewState property provides a dictionary object for retaining values between multiple requests for
the same page. This is the default method that Web pages use to preserve page and control property
values between round trips.
When the page is processed, the current state of the page and controls is encoded and the resulting
string is saved in the page as a hidden field. If the amount of data that is stored in the ViewState
property exceeds the value specified in the MaxPageStateFieldLength property, the string is saved in
the page as multiple hidden fields. When the page is posted back to the server, the page parses the view
state string at page initialization and restores property information.
The information in this topic describes best practices that will help you improve the security of
application data that is stored in view state.
While following coding and configuration best practices can improve the security of your application, it
is also important that you continually keep your Web server computer up to date with the latest security

25

updates for Microsoft Windows and Internet Information Services (IIS), as well as any security updates
for Microsoft SQL Server or other membership data sources.
More detailed information about best practices for writing secure code and securing applications can be
found in the book "Writing Secure Code" by Michael Howard and David LeBlanc, or through the
guidance provided by Microsoft Patterns and Practices.
Securing View State Data on the Page
By default, view state data is stored on the page in a hidden field and is encoded using base64 encoding.
In addition, a hash is created from the data using a machine authentication code (MAC) key. The hash
value is added to the encoded view state data and the resulting string is stored on the page. When the
page is posted back to the server, the ASP.NET page framework re-hashes the view state data and
compares the hash with the hash stored previously in the page. If the hash does not match, an exception
is raised indicating that view state data might be invalid.
By creating a hash value, the ASP.NET page framework can test whether the view state data has been
tampered with. But view state data can still be viewed, and can potentially be intercepted and read by
malicious users.
MAC Encoding
When the ASP.NET page framework creates a hash for view state data, it uses a MAC key that is either
auto-generated or specified in the Machine.config file. If the key is auto-generated, it is created based
on the MAC address of the computer. The MAC address is the unique GUID value of the network
adapter in the computer.
It can be difficult for malicious users to reverse-engineer the MAC key based on the value in the page
and the view state. Thus, MAC encoding is typically a reliable way to determine whether anyone has
tampered with the view-state data.
In general, the larger the MAC key that is used to generate the hash, the less likely it is that the hash
value for different strings will be the same. When the key is auto-generated, ASP.NET uses SHA1
encoding to create a large key. However, in a Web-farm environment, the key must be the same across
all of the servers. If the key is not the same, and the page is posted back to a different server than the
one that created the page, the ASP.NET page framework will raise an exception. Therefore, in a Web
farm environment, you should specify a key in the Machine.config file instead of allowing ASP.NET to
auto-generate one. The longer the key, the more secure it is; but the longer the key is the more time it
takes to create a hash, so it is important to weigh security needs versus performance needs.

26

Encryption
While MAC encoding helps prevent tampering with view state data, it does not prevent users from
viewing the data. View state data is stored in one or more hidden fields on the page and is encoded
using base64 encoding. You can prevent people from viewing this data in two ways: transmitting the
page over SSL and by encrypting the view state data. Requiring the page to be sent over SSL can help
prevent data-packet sniffing and unauthorized data access by people who are not the intended recipients
of the page.
However, the user who requested the page can still view the view state data because SSL decrypts the
page to display it in the browser. This is fine if you are protecting the data primarily from people who
should not be allowed to see the page and are not concerned about authorized users having access to
view state data. However, in some cases controls might use view state to store information that no users
should have access to. For example, the page might contain a data-bound control that stores item
identifiers (data keys) in view state. If those identifiers contain sensitive data, such as social security
numbers of customer IDs, you should encrypt the view-state data in addition or instead of sending over
SSL.
To encrypt the data, set the page's ViewStateEncryptionMode property to true. If you store information
in view state, you can use normal read and write techniques; the page handles all encryption and
decryption for you. Encrypting view state data can affect the performance of your application, so do not
use encryption unless you need it.
Control State Encryption
Web controls can maintain small amounts of data, called control state, that are required for the correct
operation of the control. When a control uses control state, a view state field containing the control state
is sent to the client on each request even when view state is turned off for the application or page.
Controls that use control state can require that view state be encrypted by calling the
RegisterRequiresViewStateEncryption method. If any control on the page requires that view state be
encrypted, then all view state on the page will be encrypted.
Per-user View State Encoding
If your Web site authenticates users, you can set the ViewStateUserKey property in the Page_Init event
handler to associate the page's view state with a specific user. This helps prevent one-click attacks, in
which a malicious user creates a valid, pre-filled Web page with view state from a previously created
page. The attacker then lures a victim into clicking a link that sends the page to the server using the
victim's identity.
When the ViewStateUserKey property is set, the attacker's identity is used to create the hash of the
view state of the original page. When the victim is lured into resending the page, the hash values will be

27

different because the user keys are different. The page will fail verification and an exception will be
thrown.
You must the ViewStateUserKey property to a unique value for each user, such as the user name or
identifier.
Securing Configuration in Shared Hosting Environment
In a shared hosting environment, malicious users can potentially modify state-management properties
that might affect other applications on the computer. This can be done through direct modification to the
Machine.config file, modification via the configuration APIs, and other administration and
configuration tools. You can help prevent modification to your application configuration by encrypting
sections of configuration files. For more information, see Encrypting Configuration Information Using
Protected Configuration

Another Answer
Protecting the View State from Modification
Even though view state should only store the state of the Web controls on the page and other nonsensitive data, nefarious users could cause you headaches if they could successfully modify the view
state for a page. For example, imagine that you ran an eCommerce Web site that used a DataGrid to
display a list of products for sale along with their cost. Unless you set the DataGrid's EnableViewState
property to False, the DataGrid's contentsthe names and prices of your merchandisewill be
persisted in the view state.
Nefarious users could parse the view state, modify the prices so they all read $0.01, and then deserialize
the view state back to a base-64 encoded string. They could then send out e-mail messages or post links
that, when clicked, submitted a form that sent the user to your product listing page, passing along the
altered view state in the HTTP POST headers. Your page would read the view state and display the
DataGrid data based on this view state. The end result? You'd have a lot of customers thinking they
were going to be able to buy your products for only a penny!
A simple means to protect against this sort of tampering is to use a machine authentication check, or
MAC. Machine authentication checks are designed to ensure that the data received by a computer is the
same data that it transmitted outnamely, that it hasn't been tampered with. This is precisely what we
want to do with the view state. With ASP.NET view state, the LosFormatter performs a MAC by
hashing the view state data being serialized, and appending this hash to the end of the view state. (A

28

hash is a quickly computed digest that is commonly used in symmetric security scenarios to ensure
message integrity.) When the Web page is posted back, the LosFormatter checks to ensure that the
appended hash matches up with the hashed value of the deserialized view state. If it does not match up,
the view state has been changed en route.
By default, the LosFormatter class applies the MAC. You can, however, customize whether or not the
MAC occurs by setting the Page class's EnableViewStateMac property. The default, True, indicates that
the MAC should take place; a value of False indicates that it should not. You can further customize the
MAC by specifying what hashing algorithm should be employed. In the machine.config file, search for
the <machineKey> element's validation attribute. The default hashing algorithm used is SHA1, but you
can change it to MD5 if you like. (For more information on the SHA1, see RFC 3174; for more
information on MD5, read RFC 1321.)
Note When using Server.Transfer() you may find you receive a problem with view state
authentication. A number of articles online have mentioned that the only workaround is to set
EnableViewStateMac to False. While this will certainly solve the problem, it opens up a security hole.
For more information, including a secure workaround, consult this KB article.
Encrypting the View State
Ideally the view state should not need to be encrypted, as it should never contain sensitive information.
If needed, however, the LosFormatter does provide limited encryption support. The LosFormatter only
allows for a single type of encryption: Triple DES. To indicate that the view state should be encrypted,
set the <machineKey> element's validation attribute in the machine.config file to 3DES.
In addition to the validation attribute, the <machineKey> element contains validationKey and
decryptionKey attributes, as well. The validationKey attribute specifies the key used for the MAC;
decryptionKey indicates the key used in the Triple DES encryption. By default, these attributes are set
to the value "AutoGenerate,IsolateApp," which uniquely autogenerates the keys for each Web
application on the server. This setting works well for a single Web server environment, but if you have a
Web farm, it's vital that all Web servers use the same keys for MAC and/or encryption and decryption.
In this case you'll need to manually enter a shared key among the servers in the Web farm. For more
information on this process, and the <machineKey> element in general, refer to the <machineKey>
technical documentation and Susan Warren's article Taking a Bite Out of ASP.NET ViewState.
The ViewStateUserKey Property
Microsoft ASP.NET version 1.1 added an additional Page class propertyViewStateUserKey. This
property, if used, must be assigned a string value in the initialization stage of the page life cycle (in the

29

Page_Init event handler). The point of the property is to assign some user-specific key to the view state,
such as a username. The ViewStateUserKey, if provided, is used as a salt to the hash during the MAC.
What the ViewStateUserKey property protects against is the case where a nefarious user visits a page,
gathers the view state, and then entices a user to visit the same page, passing in their view state (see
Figure 10). For more information on this property and its application, refer to Building Secure
ASP.NET Pages and Controls.

30

Figure 10. Protecting against attacks using ViewStateUserKey

31

Conclusion
In this article we examined the ASP.NET view state, studying not only its purpose, but also its
functionality. To best understand how view state works, it is important to have a firm grasp on the
ASP.NET page life cycle, which includes stages for loading and saving the view state. In our
discussions on the page life cycle, we saw that certain stagessuch as loading postback data and
raising postback eventswere not in any way related to view state.
While view state enables state to be effortlessly persisted across postbacks, it comes at a cost, and that
cost is page bloat. Since the view state data is persisted to a hidden form field, view state can easily add
tens of kilobytes of data to a Web page, thereby increasing both the download and upload times for Web
pages. To cut back on the page weight imposed by view state, you can selectively instruct various Web
controls not to record their view state by setting the EnableViewState property to False. In fact, view
state can be turned off for an entire page by setting the EnableViewState property to false in the @Page
directive. In addition to turning off view state at the page-level or control-level, you can also specify an
alternate backing store for view state, such as the Web server's file system.
This article wrapped up with a look at security concerns with view state. By default, the view state
performs a MAC to ensure that the view state hasn't been tampered with between postbacks. ASP.NET
1.1 provides the ViewStateUserKey property to add an additional level of security. The view state's data
can be encrypted using the Triple DES encryption algorithm, as well.

Whats the use of @ Register directives ?


@ Register
Creates an association between a tag prefix and a custom control, which provides developers with a
concise way to refer to custom controls in an ASP.NET application file (including Web pages, user
controls, and master pages).
<%@ Register tagprefix="tagprefix" namespace="namespace" assembly="assembly" %> <%@
Register tagprefix="tagprefix" namespace="namespace" %> <%@ Register tagprefix="tagprefix"
tagname="tagname" src="pathname" %>
Attributes
assembly
The assembly in which the namespace associated with the tagprefix attribute resides.
Note
The assembly name cannot include a file extension. Also note that if the assembly attribute is missing,

32

the ASP.NET parser assumes that there is source code in the App_Code folder of the application. If you
have source code for a control that you want to register on a page without having to compile it, place
the source code in the App_Code folder. ASP.NET dynamically compiles source files in the App_Code
folder at run time.
namespace
The namespace of the custom control that is being registered.
src
The location (relative or absolute) of the declarative ASP.NET User Controls file to associate
with the tagprefix:tagname pair.
tagname
An arbitrary alias to associate with a class. This attribute is only used for user controls.
tagprefix
An arbitrary alias that provides a shorthand reference to the namespace of the markup being
used in the file that contains the directive.
Remarks
Including the @ Register directive in a page or user control allows you to lay out custom server
controls or user controls using declarative Custom Server Control Syntax.
Note
You can also register custom controls on all the pages of an application by using the controls Element
for pages (ASP.NET Settings Schema) in the Web.config file.
Use the @ Register directive in the following situations:

To add a custom server control declaratively to a Web page, a user control, a master page, or a
skin file (see ASP.NET Themes and Skins Overview).

To add a user control declaratively to a Web page, a user control, a master page, or a skin file.

Note
The tagprefix value "mobile" is used by ASP.NET to identify the mobile Web controls in the
System.Web.UI.MobileControls namespace. You should avoid using this prefix for your controls.
When you use the @ Register directive to reference a control, you can place the code for the control in
the following places:

As source code in the application's App_Code folder, where it will be dynamically compiled
at run time. This is a convenient option during development. If you choose this option, you do
not use the assembly attribute in the @ Register directive.

33

As a compiled assembly in the application's Bin folder. This is a common option for deployed
Web applications.

As a compiled and signed assembly in the global assembly cache (GAC). This is a common
option if you want to share a compiled control among multiple applications. You can
reference a control in the GAC by assigning an identifying string to the assembly attribute.
The string specifies the required details about the control, including its fully qualified type
name, its version, its public key token, and its culture. The following fictional string illustrates
a reference to a custom control in the GAC:
Copy Code
<%@ Register tagprefix="custom" namespace="Mycompany.namespace"
assembly="Mycompany.namespace.control, Version=1.2.3.4,
PublicKeyToken=12345678abcdefgh, Culture=neutral" %>
For more information about referencing assemblies, see add Element for assemblies for
compilation (ASP.NET Settings Schema).

For declarative user controls, use the tagname, tagprefix, and src attributes. The first two are always
used together as a colon-separated pair (tagprefix:tagname) when you declare the control in the page.
You can map multiple namespaces to the same tagname, as in the following example:
Copy Code
<% @Register tagprefix="tag1" namespace="MyNamespace1"/> <% @Register tagprefix="tag1"
namespace="MyNamespace2"/>
The src attribute value can be either a relative or an absolute path to the user control source file from
your application's root directory. For ease of use, it is recommended you use a relative path. For
example, assume you store all your application's user control files in a \Usercontrol directory that is a
subdirectory of your application root. To include the user control found in a Usercontrol1.ascx file,
include the following in the @ Register directive:
Copy Code
Src="~\usercontrol\usercontrol1.ascx"
The tilde (~) character represents the root directory of the application.
Note
If your user control is in the same directory as the page that contains it, the src attribute value should be
the name and extension of the .ascx file.

34

When including custom server controls that you have compiled into a .dll file for use with your
application, use the tagprefix attribute with the assembly and namespace attributes. If you do not
include the namespace attribute, or if you assign an empty string ("") to it, a parser error will occur.
Caution
When you develop a custom server control, you must include it in a namespace. If you do not, it will
not be accessible from an ASP.NET page. For more information about developing custom ASP.NET
server controls, see Developing Custom ASP.NET Server Controls.
Example
The following code example uses @ Register directives to declare tagprefix and tagname aliases,
along with assigning a src attribute, to reference a user control within a Web page. The first part of the
code is a simple user control consisting of an ASP.NET Calendar control. The second portion of the
code is a page that hosts the control. Note that the tagprefix attribute assigns an arbitrary prefix value
to use with the tag. The tagname attribute uses the value of the class name assigned to the user control
(although the value of this attribute is arbitrary and any string value can be used--you do not have to use
the class name of the control being referenced). The src attribute points to the source file for the user
control, relative to the application root folder. The user control is referenced within the body of the page
by using the prefix, a colon, and the name of the tag, in this form: <uc1:CalendarUserControl
runat="server" />.
Copy Code
<%@ Control ClassName="CalendarUserControl" %> <asp:calendar id="Calendar1"
runat="server" /> <%@ Page %> <%@ register tagprefix="uc1" tagname="CalendarUserControl"
src="~/CalendarUserControl.ascx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head
runat="server"> <title>Calendar Page</title> </head> <body> <form id="form1" runat="server">
<uc1:calendarusercontrol runat="server" /> </form> </body> </html>

Whats the use of SmartNavigation property ?

35

You might also like