ASP Tutorial Lesson 9: Sessions

Sessions have been given a bit of a bad name but they are still useful if used with careful consideration.

A session deals with the time a user is visiting your site. By default, when a user visits a page on your site a new session begins and they are allocated an ID to identify them while they are visiting. When the user closes their browser or after a set amount of time (usually around 20mins) their session ends. Their session ID is stored in a cookie on the users machine. Later versions of ASP allow more flexibility, with ASP.NET even allowing the session information to be stored on another machine.

While a session is open you can store information in the servers memory for them, much like a dictionary. This is done like in the following;


According to Microsoft:

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

This is not to be confused with session variables.

There are problems with classic ASP sessions such as memory hogging and the information being fixed to the machine you first visit, making problems for efficient load-balancing, etc. This meant people ended up developing their own session/state management options. For smaller sites with few visitors or web farms that allow users to return to the same server this shouldn’t be as much of a problem and as I say earlier, ASP.NET has a lot more flexible options.

Here’s a great tutorial video on the difference between ViewState, SessionState and ApplicationState in