ASP.NET

ASP.NET and Session State

Since its inception, ASP.NET has supported session state. When session state is turned on, ASP.NET creates a new Session object for each new request. The Session object becomes part of the context (and is available through the page). ASP.NET stamps the Session object with an identifier (more on that later), and the Session object is reconstituted when a request comes through containing a valid session identifier. The Session object follows the page around and becomes a convenient repository for storing information that has to survive throughout the session (and not simply for the duration of the page).

The Session object is a dictionary of name-value pairs. You can associate any CLR-based object with a key of your choosing and place it in the Session object so it will be there when the next request belonging to that session comes through. Then you may access that piece of data using the key under which it was stored. For example, if you wanted to store some information provided by the user in the Session object, you'd write code like this:

void StoreInfoInSession()
{
   String strFromUser = TextBox1.Text;
   Session["strFromUser"] = strFromUser;
}

To retrieve the string during the next request, you'd use code like this:

void GetInfoFromSession()
{
   String strFromUser = Session["strFromUser"] ;
   TextBox1.Text = strFromUser;
}

The square braces on the Session object indicate an indexer. The indexer is a convenient syntax for express keys-both when inserting data into and retrieving data from the Session object.

Managing session state in ASP.NET is extraordinarily convenient. In ASP.NET, session state may live in a number of places including (1) in proc-in the ASP.NET worker process, (2) on a separate state server running a daemon process, and (3) in a SQL Server database.

Let's start by getting a taste of using session state right now.