Database Search Solution
(New Version) Search Control
Free ASP.NET Controls
ASP.NET Media Player Control
Flash Video Player Control
ASP.NET Telecommute Jobs
Free IP Location Lookup
Test .Net Regular Expressions
CSS/Table/DIV Page Layouts
Article Sites Master List
.NET Windows Forms
General .NET Framework
Accepting Credit Cards
ASP.NET Session Explored
HTTP protocol, used for communication between web browser and web server, can't track individual visitor between two requests. All what web server can do when receives request, is to return some bytes back to browser. That sequence of bytes usually represents textual data like HTML, XML, or binary data like images, .zip files etc. After web server returns data, connection is closed and all visitors' information is discarded.
That means, if single visitor opens first page, and then goes to second page of same website, HTTP protocol can't say is it the same visitor or two different visitors. We say that HTTP protocol is stateless.
But, some types of websites, like social network or ecommerce site, require identification of each visitor. To solve this problem, ASP.NET offers Session State as a method how web application can save data about individual visitor between requests while using stateless HTTP protocol.
What is ASP.NET Session State?
ASP.NET Session State is represented with Session object. Session object is type of System.Web.SessionState.HttpSessionState. You can access to this object anywhere in server code using HttpContext.Current.Session and additionally from ASP.NET page using Page.Session.
To store some information specific to individual user, you can use code like this:
[ C# ]
// First we need to save information to session state variable
[ VB.NET ]
' First we need to save information to session state variable
As you see, basic syntax is very simple. You don't need to declare session variable to use it. Just place save some value and ASP.NET will create new session variable if it not exists already.
Note that hard coded session variable names like in previous code sample could lead to numerous problems with scalability, debugging, maintenance etc. More about these problems and how to read and write session variables on correct way see in How To Write, Read and Delete Session State Variables tutorial.
Session state is collection of objects, separated for each visitor. When some visitor opens a web page, ASP.NET creates new session state collection for that visitor. Next visitor will get new session state collection etc. Collection members are type of System.Object, so collection could contain any .Net type.
Stored values could be simple types like string or integer, but also practically anything like business objects, controls, classes etc. All session data will persist between page requests until session expires.
ASP.NET session expiration
Session represents single website visit, or at least tries to. In practice, due to stateless nature of HTTP protocol, ASP.NET can't know when visit is finished. ASP.NET can't find out if visitor closed browser or just doing something else (like talking on the phone) and will return after a while. To solve this problem, architects of ASP.NET introduced session expiration. Simply, if there is no new request from same visitor for certain time period, visit will be considered as finished. Default session expiration time is 20 minutes. So, if visitor doesn't make any request in 20 minutes, session will expire.
When session expires, all session data for that visitor are deleted. Automatic deletion of data is necessary to save web server's resources. Otherwise, visitors' data would overburden server. But, deletion could also lead to application's errors which are hard to discover. To learn more about how to deal with session expiration and how to keep session alive for active visitors only, read How To Keep ASP.NET Session Alive tutorial. Different methods about how to check if session is already expired, so you can avoid potential errors are described in How to find if ASP.NET session is expired tutorial.
Default 20 minutes timeout can be changed using Session.Timeout property. This could be done in web.config file, in code at run time or using IIS settings. How To Change ASP.NET Session Timeout
Every time when visitor opens new page, session timer is restarted. If visitor continuously makes new requests, session will never expire. Session could also expire programmatically if it is deleted using ASP.NET server side code, by calling Session.Abandon() method.
How ASP.NET Session State really works?
Session state variables are stored on server side. Each visitor has its own collection of variables. But, how ASP.NET knows which collection belongs to each visitor?
As we know, HTTP is stateless protocol which doesn't provide this information. And, because ASP.NET websites are also accessed using this stateless HTTP, logical question is how ASP.NET Session State identifies visitors?
The idea is actually very simple: when someone visits .aspx page, ASP.NET stores a cookie, named ASP.NET_SessionId, on visitor's computer. This cookie contains a unique string, called session id. ASP.NET also stores same string in server's memory. When visitor opens next page, ASP.NET reads that cookie and compares cookie value with value stored on server side. If both values of session id are same, ASP.NET "recognizes" the visitor.
Of course, what ASP.NET actually does, is just comparing two strings: first stored on client side (in cookie) and second stored on server side (in server's memory). That could be security risk. Session id is just a plain string, stored in a cookie which can be read easily. If malicious user obtains session id of some active user, and uses it to make request to website, ASP.NET will consider both visitors as regular user. On this way, malicious user possibly could see private data or have access to restricted areas of website.
Session data are not secured, especially if session cookie is not marked as secure, or if cookieless="true" is used. If you need secure identification, use Forms or Windows authentication. All session state data should be considered as public.
After some time of inactivity session expires on server side which practically means that session data are deleted. Session cookie still remains on client side. If session is expired, new request of same visitor will create new session, despite session cookie already exists.
If client has disabled cookies or browser not supports them, ASP.NET session state can't create it or read cookie value, and finally it can't identify individual visitor. In this case, new session with new session id will be created for every request. That happens for example, if search engine robots visit website, because robots usually don't support cookies.
ASP.NET Session State is implemented as HTTP module (System.Web.SessionState.SessionStateModule, specified in machine.config, inside <httpModules> element). This module attaches session data into HTTP context on every request. This happens before page is instantiated, so any code behind will be able to read session variables from Session object.
Session State modes
By default, session variables are stored in web server's memory inside of ASP.NET working process. This method has many drawbacks. If web application is restarted or recycled, session data will be lost. Also, it is hard to store session inside of process if website is running on multiple processes (e.g. web farms or web gardens). High traffic websites could slow down if sessions take to much memory etc.
To solve all these issues, ASP.NET provides five different modes:
- Off - to disable Session State if not needed
For more detailed comparison of session state modes, and to know which mode to choose in specific case, check ASP.NET Session State Modes Explained tutorial.
Cookieless ASP.NET session
Cookieless sessions could cause problems with search engines and security problems. More about working with cookieless sessions you can read in Cookieless Session State Explained tutorial.
ASP.NET session events in Global.asax file
When new session is created, ASP.NET executes Session_Start procedure in Global.asax file. When session is destroyed, Session_End procedure is executed.
Session_Start event will fire every time. But, Session_End event will fire only if default InProc mode is used. If you use any of out of process modes, like StateServer, SQLServer or Custom, Session_End event will be ignored.
Session state compression
ASP.NET 4.0 supports new compressionEnabled parameter. If compressionEnabled="true", ASP.NET will use gzip (open source GNU zip, in .Net Framework implemented in System.IO.Compression.GZipStream class) to compress session state and save server resources.
Implementation looks like this:
<sessionState compressionEnabled="true" />
How much data will be smaller after compression depends of what kind of data are stored in session variables.
ASP.NET Session State is simple way to save visitor specific data between requests. But, session is not best solution in every scenario. For example, if session data should persist between visits, then you can use some alternative, like store data in persistent cookies or use Profile class. More about advantages and disadvantages of ASP.NET sessions you can find in Session State Advantages & Disadvantages tutorial. If ASP.NET Session State can't satisfy your current project requirements, then you must select appropriate alternative. Detailed review of Session State alternatives read in ASP.NET Session State Alternatives tutorial.
Using of ASP.NET Session State could be potential security risk. More about different risks when using sessions, and specific threats for each session state mode you can read in ASP.NET Session State Security tutorial.
comments powered by Disqus