Вы находитесь на странице: 1из 8

ASPAlliance: Articles, reviews, and samples for .

NET
DevelopersURL:
http://aspalliance.com/articleViewer.aspx?aId=1066&pId=-1

Top of Form
/w EPDw UJNDQ1

Session State Management

page

by Joydip Kanjilal
Feedback

Average Rating:
Views (Total / Last 10 Days): 60523/ 175

Introduction
ASP.NET, like traditional ASP, provides the facility to track a user's session using Session State.
Web applications are built on Hypertext Transfer Protocol (HTTP). HTTP being a stateless
protocol, each request to the server from the client is understood as an independent request.
ASP.NET provides a powerful way to store a user’s session specific data using the Session State
which is accessible as long as the user’s session is alive. This article discusses Session State, its
advantages and disadvantages, the Session storage modes and how we can configure the same
using the application’s web.config file.
Session, Session ID and Session State
A Session is defined as a session or the duration of connectivity between a client and a server
application. A Session object is created and maintained on the web server and is unique to a
user’s session of communication with the web server. Note that an object must be serializable in
order to be persisted in the Session object.
When a Session starts, the browser sends a cookie with a session identifier along with every
request. The IIS web server uses this Session ID to determine whether it belongs to an existing
session. If none is found, a Session ID (120 - bit string) is generated along with the request. The
Session ID persists as long as the browser session is alive even though the session state expires
after the specified timeout. Hence, the same session ID can represent multiple sessions over
time where the browser instance is the same.
Session State is a collection of objects that are stored in the memory of the web server. But
where is the Session State stored? In II5, Session State is stored in the memory of the process
aspnet_wp.exe. In IIS6, by default all applications share the same application pool, i.e. the
session state is stored in the memory of the process w3wp.exe. They are not isolated per
application basis, but instead per application pool (w3wp.exe).
Advantages and disadvantages of Session State
The advantages of using session state are as follows:
• Process independence
• Ease of implementation
• Durability
• Scalability
The disadvantages of using session state are:
• Low Performance for large volumes of data
• Overhead involved for serializing and de-serializing the Session data
Storing Session State in ASP.NET
Session state in ASP.NET can be stored in one of the following three ways.
• InProc
• State Server
• SQL Server
Session state can be configured using the <sessionState> section in the application's web.config
file. Hence, we can increase the default Session timeout value to our desired value using the
following statement in the web.config file.
Listing 1
<sessionState
timeout="40"
/>
The above statement doubles the Session Timeout value from 20 minutes to 40 minutes. Note
that the Session Timeout value is a Sliding expiration one.
The following is the complete syntax for specifying Session State in the web.config file using
the mode attribute.
Listing 2
<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
cookieless = <"true" | "false">
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL
connection string that is only used in the SQLServer mode>
server = <The server name that is
only required when the mode is State Server>
port = <The port number that is only
required when the mode is State Server>
The following section discusses each of the settings shown in Listing 1 earlier, in detail.
Mode: This setting supports three options. They are inproc, sqlserver, and stateserver. As stated
earlier, ASP.NET supports two modes: in process and out of process. There are also two options
for out-of-process state management: memory based (stateserver) and SQL Server based
(sqlserver).
Cookieless: This setting takes a boolean value of either true or false to indicate whether the
Session is a cookieless one.
Timeout: This indicates the Session timeout vale in minutes. This is the duration for which a
user's session is active. Note that the session timeout is a sliding value; on each request the
timeout period is set to the current time plus the timeout value.
SqlConnectionString: This identifies the database connection string that names the database used
for mode sqlserver.
Server: In the out-of-process mode stateserver, it names the server that is running the required
Windows NT service: ASPState.
Port: This identifies the port number that corresponds to the server setting for mode State Server.
Note that a port is an unsigned integer that uniquely identifies a process running over a network.
Storing Session State in the InProc Mode
The InProc mode of Session State storage is the fastest among all of the storage modes available
and stores the Session data in the ASP.NET worker process. In this case, if the amount of data
that is stored in the Session is large, performance would be drastically affected. In the InProc
mode of Session state storage, the session state is stored in the memory space of an application
domain and is volatile. In this case, the session state will be lost if the ASP.NET worker process
named aspnet_wp.exe recycles or if the application domain restarts. The Session State here
entirely depends on the lifetime of the application domain that it runs on. Note that the
Session_End event which is fired internally by the web server is supported only in InProc mode.
Note that even if the Session State is set to read only using the EnableSessionState attribute, in
the InProc mode one can still modify the session. The Session_OnEnd event is invoked by the
runtime environment when we make a call to the Session.Abandon() method or when the user's
session times out. Further, any change made in the settings in the web.config file unloads the
application domain and the Session State too.
Storing Session State in a State Server
The StateServer mode uses a stand-alone Microsoft Windows service that is independent of IIS
and can run on a separate server. In the State Server mode of Session State storage, the session
state is serialized and stored in memory in a separate process that is managed by the
aspnet_state.exe file. Note that State Server can be on a different system. This storage mode
has some performance drawbacks due to the overhead involved in serialization and de-
serialization of objects. Note that the ASP.NET State Service is like any other NT/2000 service
and runs as its own process and has its own memory space.
The following is the required setting in the web.config file to store the Session State in the State
Server mode.
Listing 3
<sessionState mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=joydip;password=joydip"
cookieless="false" timeout="20"/>
The primary advantage of storing the Session State in a State Server is that it is not in the same
process as the ASP.NET and a crash of ASP.NET would in no way destroy the session data.
Secondly, this mode of Session State storage enables to share the information across a web
garden or a web farm.
The main disadvantage, however, is that this mode is slow compared to the InProc mode as it is
stored in an external process.
Storing Session State using SQL Server
The SQL Server mode of Session State storage offers a reliable, secure and centralized storage
of a session state with transactional facilities. In this storage mode, the Session data is serialized
and stored in a database table in the SQL Server database. It can typically be used in the web
farms. In the SQL Server mode of Session State storage, the session state is serialized and
stored in the SQL Server. It has performance bottlenecks as in the State Server mode of Session
State storage due to the overhead involved in serialization and de-serialization of the objects that
are stored and retrieved to and from the Session. SQL Server is more secure than the InProc or
the State server modes of Session State storages as the data can be secured easily by configuring
the SQL Server security.
The InstallSqlState.sql file has to be located in the system and executed. This would create the
necessary database and tables in the tempdb database to store the Session data. To remove all
the databases and the tables created earlier using the InstallSqlState.sql file, the
UninstallSQLState.sql file can be used. The web.config file has to be modified accordingly.
The following is the required setting in the web.config file to store the Session State in the SQL
Server mode.
Listing 4
<sessionState mode="SQLServer"
sqlConnectionString="data source=server;user id=joydip;password=joydip"
cookieless="false" timeout="20" />
Okay, but which one should I choose?
So, which one to choose? Which Session state storage mode is the best? We have to choose
between speed, reliability, security and scalability.
For sites that run in a single server, the InProc storage mode in the best. It is the fastest of all the
three modes, but it has its own limitations. The major problem is that it is volatile. In the InProc
mode of storage, the durability of the data that is stored in the Session State is dependent on the
life time Application Domain that the application runs in. Once the Application Domain restarts
or shuts down, the Session is lost. In a production environment, the InProc mode of Session
State storage is not feasible. When we have to go for WebFarms, the OutProc mode is the best;
especially when the traffic is heavy on the site. The SQLServer mode of storage is suited when
we need to secure the Session data or when we require scalability and reliability, but it takes
more time to store and retrieve data to and from the database table. We have to decide the right
type of Session state storage mode based on the context by choosing between speed, scalability,
and reliability.
Sharing Session State between Classic ASP and ASP.NET
ASP and ASP.NET sessions are not easily shareable. Sharing session state between Classic ASP
and ASP.NET can be possible through one of the following ways:
• Storing the data in a common database or in the cookies
• Passing the data from one page to another page using query strings
• Using a 3rd party component for sharing session data
Storing, retrieving and deleting objects in the Session
In order to add objects from the Session use the following method:
Listing 5
HttpSessionState.Session.Add(name,value);
This adds an object to the Session state, the name and the value of the item to be added being
passed to this method as parameters. Further, the HttpSessionState class is present in the
System.Web namespace in the System.Web.dll file.
Alternatively, we can add objects to the Session.
Listing 6
HttpSessionState.Session[“UserName”] = “Joydip”;
This automatically creates a new item called “UserName” in the Session State Collection (if
none exists) and sets its value to “Joydip.”
The following method is used to retrieve a previously stored object from the Session state.
Listing 7
string userName = HttpSessionState.Session["UserName"].ToString();
Note that the ToString() method is called because data is stored in the Session state as objects.
Therefore, the conversion or casting to the appropriate type is necessary in the above example to
retrieve the current User’s name as a string.
The following method is used to remove an object from the Session state.
HttpSessionState.Remove(objectName);
This method deletes the object specified as parameter from the Session State Collection,
provided the same exists. In this case, if the session-state collection does not contain the element
specified, the collection remains unchanged, but no exception is thrown.
To clear the Session use either of the following:
Session.Abandon();
or
Session.Clear();
The difference between the Session.Abandon() and the Session.Clear() method is that if you call
Session.Abandon(), Session_End will be fired (for InProc mode) and in the next request,
Session_Start will be fired. Session.Clear( ) just clears the session data without killing it.
Enabling and disabling Session State in ASP.NET
Session State in ASP.NET can be enabled and disabled both at the page and application levels.
This section discusses how we can enable and disable Session state at both the page and
application levels.
Page Level
We can disable Session State for the pages that do not require access to Session data using the
EnableSessionState statement in the Page directive of a page as shown below.
Listing 8
<%@ Page EnableSessionState="False" %>
Session State for a page can also be set to read only for pages that require access to the Session
data, but do not modify them. Refer to the statement below.
Listing 9
<%@ Page EnableSessionState="ReadOnly" %>
Application Level
Session State can also be disabled for all the pages of the application by specifying the same at
the application level in the configurations section of the web.config file.
Listing 10
<configuration>
<system.web>
<pages enableSessionState="false" />
</system.web>
</configuration>
It is also possible to set the Session State to read-only for all the pages in the application.
Listing 11
<configuration>
<system.web>
<pages enableSessionState="ReadOnly" />
</system.web>
</configuration>
Points to remember
This section discusses some important points that one should keep in mind when working with
Session State in ASP.NET. I have put together some of the most important points here.
1. We should be well aware of the amount of the data that we store in the Session, particularly
for sites that have a heavy traffic. In a distributed web server environment, the use of Session
variables can degrade performance.
2. The Session IDs are stored in the Cookies in the Client side and are used for communication
between the Server and the Client. If the Session does not contain a Cookie, the Session ID is
maintained using the URL only.
3. It should be noted that the SessionID lasts as long as the user’s session of communication
with the web server is active, i.e., as long as the browser instance is unchanged. This can happen
even after expiry of the Session after the specified timeout period. Note that if the application
has never stored anything in the session state, a new session state with a new Session ID is
created with every request. In SQLServer mode of Session State storage, the session expiration
is carried out by the SQL Agent using a registered job.
4. The Session timeout value is specified web.config file. It is a sliding expiration value and
indicates the time (in minutes) that the Session can be idle before it is abandoned. When a
session times out, the session data is flushed out, the Session object is killed and a new one is
created on a subsequent hit to the page. The Session timeout value is a sliding expiration value.
5. Note that the Session state is available only after the HttpApplication.AcquireRequestState
event is called. The Session_End event is supported only in the InProc mode and is fired
internally by the Web Server, based on an internal timer. Thus, there is no HttpRequest that is
associated when that happens. This is why the methods Response.Redirect or Server.Transfer
do not work in the Session_End event. The Session_OnEnd event is called when we make a call
to the Session.Abandon method or when the Session times out.
6. Storing the basic types in the Session state is much faster compared to storing object types
due to the serialization and de-serialization overhead involved.
7. The IsNewSession property of the HttpSessionState class can be used to detect whether a
Session has timed out or was abandoned.
8. Remember never to use a Response.Redirect or Server.Transfer method call after you set the
Session in the login page of your application. Both these methods call the Response.End method
internally. The Session ID would be lost as the Response.End method stops execution of the
page. Use the FormsAuthentication.RedirectFromLoginPage method instead. Alternatively, you
can use the following overloaded version of the Response.Redirect method.
9. Response.Redirect("~/menu.aspx", false)
10. This would not abort the current thread and would prevent the Session ID from being lost.
Suggested Readings
State Management in ASP.NET
ASP.NET Session Management Internals
State Management in ASP.NET
ASP.NET offers new state management techniques
Session State -- MSDN
Session State Overview -- MSDN
Custom session state management in ASP.NET 1.1
Conclusion
Session State is an often misunderstood concept to the ASP.NET professionals. Often we make
mistakes in selecting when to use the Session or store data in the Session. The proper selection
of Session State Storage mechanism is also absolutely essential for a web application. ASP.NET
provides three session state storage modes: In-Proc, State Server, and SQL Server. This article
has discussed all three Session State storage modes in detail with code examples whenever
necessary. It has also discussed the pros and cons of using the Session State to store user data. It
should be noted that we should choose the right type of the Session Storage mode for our
application and at the same time ensure that we store the right type of the objects in the Session.
Storing too many objects in the Session would degrade the performance of the application to a
great extent. I welcome readers' comments and suggestions.

Product Spotlight

SpreadsheetGear: ASP.NET Excel Reporting


Easily create richly formatted Excel reports without Excel using the new generation of
spreadsheet technology built from the ground up for scalability and reliability. learn more
Bottom of Form

©Copyright 1998-2010 ASPAlliance.com | Page Processed at 12/23/2010 4:36:30 AM


About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us |
Privacy | Search

Вам также может понравиться