Get to Know the HttpSessionState Class

Use its properties and methods to manage session state.

ITPro Today

October 30, 2009

9 Min Read
ITPro Today logo

ASP.NETis basically a stateless environment, as was ASP classic. Every time a userrequests a page, ASP.NET renders the output without any knowledge of previousrequests. To enable you to track the state of your applications, ASP.NETprovides several mechanisms at various levels. For example, the ViewStateobject allows a single page to track its own state, but ViewStatedoesn't help as users move from page to page. For more information on the ViewState object, see "ViewState of the Mind." If you've worked with ASP classicfor any length of time, you probably have encountered the Sessionobject. For more information on ASP.NET, see "HTML5 for the ASP.NET Developer" and "ASP.NET MVC Tutorial: Handling Errors and Exceptions." Among other things, this object provides a property bag in which youcan store a dictionary of name-value pairs, using code like this:

' To store a value:Session("VariableName") = Value' To retrieve a value:Value = Session("VariableName")

Inaddition, ASP classic's Session object provides the SessionID andTimeOut properties as well as an Abandon method.

InASP.NET, you can write code that takes advantage of the Session objectas you might in ASP classic - from within your VB .NET or C# code. You shouldnote, however, that the Session object you're using is now an instanceof the HttpSessionState class, and this class provides you with manyproperties and methods new in ASP.NET. This class provides access to the sametype of session-state values as you used in ASP classic, and it also providesproperties that allow you to manage session-level settings. HttpSessionStatealso provides some useful lifetime management methods. I'll provide an overviewof the HttpSessionState class, including its properties and methods. (Iwon't attempt to dig into the many concepts and details involved in managingsession state or the new out-of-process options ASP.NET provides because thesetopics require an article of their own.)

Althoughyou can write code that works with Session values in ASP.NET as youmight have written it in ASP classic, you're really working with a property ofthe Page object now. That is, when you write:

Session("VariableName") = Value

you'reactually writing:

Page.Session("VariableName") = Value. 

Thecurrent page's Session property is an HttpSessionState objectthat contains the current Session object ASP.NET provides. ASP.NETprovides the Page.Session property as a convenience for you. This isn'tcritical to your use of the Session object - you simply use the Sessionobject as you might in ASP classic - but it's nice to know where it's comingfrom.

 

Simple HttpSessionState Properties

The HttpSessionStateclass provides many simple properties you can use to retrieve information aboutthe current session. Although most of the properties are read-only, a few alsoallow you to set values. Figure 1 shows Default.aspx from this article'sdownloadable sample project (see the Download box at the beginning of thearticle for details). This page allows you to investigate most of the HttpSessionStateclass' simple properties.


Figure 1. This sample form allows you toinvestigate the simple properties of the HttpSessionState class.

The HttpSessionStateclass provides several informational properties. IsCookieless returns Trueif the SessionID value is embedded in the URL, and it returns Falseotherwise. Typically, you control this behavior by setting the appropriatevalue in your site's web.config file. If this value is True, yoursession information is available whether or not the user has enabled cookies.

IsNewSession returns True if the sessionwas created with the current request. This value should appear as Trueon the sample page the first time you display it. If you click on Submit, forcing a post-back to thecurrent page, the value should change to False (because the session nolonger is new).

IsReadOnly gets a value indicating whetherthe current session is read-only. (You can use read-only session state for apage by setting the EnableSessionState attribute in the Pagedirective to the value ReadOnly.)

Althoughthe LCID property is provided only for backward compatibility (theproperty ends up calling the LCID method of the CultureInfo classunder the covers; the Session state doesn't store this value), it's interestingand is included on the sample page. This property allows you to get or set thelocal ID of the current session.

Mode gets the current mode of thesession. It can be one of the SessionState.SessionStateMode enumeratedvalues: InProc, Off, SQLServer, or StateServer.Normally, you set this information in the site's web.config file.

The SessionIDproperty retrieves the current session ID. The session ID allows ASP.NET tolook up values in its session variables dictionary. The session ID normallypasses between client and server in a cookie named ASP.NET_SessionID. Ifthe IsCookieless property is True, ASP.NET passes this value aspart of each request, encoded in the URL.

Finally,the TimeOut property sets or retrieves the session timeout (in minutes).The default value is 20 minutes, but you can change the timeout interval bysetting this property.

But whatabout properties you might have used previously that aren't included here?ASP.NET provides certain properties for backward compatibility. CodePagereturns the code-page identifier for the current session. ASP.NET doesn'tsupply code-page information in its session state. Instead, check out the Responseobject's ContentEncoding.CodePage property. (As with the Sessionobject, the Response object of a page is actually an instance of a .NETclass: the HttpResponse class. But that's another column, for anotherday.)

Contents retrieves a reference to thecurrent session-state object. This property isn't necessary in ASP.NET but isprovided for backward compatibility.

The StaticObjectsproperty retrieves a collection of session variables declared statically withinthe Global.asax file. Generally, you won't use these objects; instead, you willuse the Session object's collection of dynamic objects.

 

Work With Session Variables

Inaddition to the simple properties you've seen already, the HttpSessionStateclass provides a range of properties and methods that let you add, retrieve,and modify session-state values. Figure 2 shows the sample page,SessionVariables.aspx, you can use to try out these members.


Figure 2. Use the SessionVariables.aspx pageto test the members of the HttpSessionState class that manage sessionvariables.

Thesample page's Load event handler runs this code:

If Not Page.IsPostBack Then  Session("LoadTime") = Now  Session("UserName") = "Mary"  Session("ItemsSold") = 13End If

Eachstatement loads a value into a session-state variable:

Session("LoadTime") = Now

Thevalue on the right-hand side of the assignment, the value being stored,generally can be most any object type. There are restrictions when usingout-of-process session management, but session variables generally areflexible.

Forbackward compatibility, though this isn't the recommended technique, you alsocan refer to the current session state, using the Contents property ofthe Session object:

Session.Contents("LoadTime") = Now

When yourefer to a session variable from VB .NET, you're actually using the class's Itemproperty, and you can reference the property explicitly if you like. In C#, Itemis the default indexer, and you'll never refer to it explicitly:

' In VB.NET only:Session.Item("LoadTime") = Now

Thevalues you retrieve from session variables are all of type System.Object,so you'll need to cast them to specific types explicitly if you're using C# orif you've turned on Option Strict in VB .NET. If you attempt to retrieve avalue that doesn't exist, the object will be Nothing (null, inC#). The sample page treats all the values as strings, for display purposes,and handles invalid session variable names. The lstKeys_SelectedIndexChangedevent handler uses this code to display the value of the selected sessionvariable (if it exists):

Dim strItem As StringDim objValue As Object strItem = lstKeys.SelectedItem.ToStringobjValue = Session(strItem) If objValue Is Nothing Then  txtName.Text = String.Empty  txtValue.Text = String.EmptyElse  txtName.Text = strItem  txtValue.Text = objValue.ToStringEnd If

The HttpSessionStateclass provides two properties that allow you to work with session variables: Count,which returns the number of items in the collection of session variables; and Keys,which returns a KeysCollection object (a collection of strings)containing a list of all the current key names stored as session values.

Thesample page provides the DisplaySessionVariables procedure, whichincludes this code that displays the list of current keys in the lstKeys listbox:

lblCount.Text = Session.Count.ToStringlstKeys.DataSource = Session.KeyslstKeys.DataBind()

The HttpSessionStateclass also provides a range of methods that allow you to manipulate the valuesstored in session state. The Add method allows you to add a single valueto the collection of session variables. This method is somewhat superfluousbecause you can add items to the collection simply by assigning the appropriatevalue. These two statements are equivalent, if the Age session variabledoesn't exist already:

Session("Age") = 46Session.Add("Age", 46) 

Next, CopyTocopies the Session object's Keys property to a one-dimensionalarray, starting at the specified index. The documentation states that thismethod copies the values, but testing shows that it instead copies the keys.The sample page uses this code to display a comma-delimited list of the keys:

Private Sub HandleKeysAsArray()  If Session.Count > 0 Then    Dim astrKeys(Session.Count - 1) As String    Session.CopyTo(astrKeys, 0)    lblKeysAsArray.Text = String.Join(", ", astrKeys)  End IfEnd Sub

The Removemethod deletes a session value, given a string key name. For example, you mightwrite code such as:

Session.Remove("ID") 

Thesample page uses this code in the btnRemove_Click procedure:

If lstKeys.SelectedIndex >= 0 Then  Session.Remove(lstKeys.SelectedItem.ToString)End If

Clearclears the sessionvariables. RemoveAll duplicates the Clear method's behavior.After calling this method, the collection of session variables contains novalues and the Count property returns 0.

RemoveAt removes a session value, given itsindex within the collection of values. This method isn't as useful as the Removemethod, but it does allow you to remove items by index. The sample page usesthis code to remove items by index:

If lstKeys.SelectedIndex >= 0 Then  Session.RemoveAt(lstKeys.SelectedIndex)End If

Finally,the HttpSessionState class provides the Abandon method, whichallows you to abandon a session and its session variables programmatically. Ofcourse, if the number of minutes specified in the TimeOut propertypasses between requests, the session ends automatically. You can force animmediate abandonment of the session by calling this method. The Abandonbutton on the sample page calls this method and then refreshes the display ofsession variables. (You might need to refresh the page twice in order to verifythat the session variables have indeed been abandoned.)

Afterworking through the examples in this article, you'll also want to investigatethe events the HttpApplication object provides. (Normally, you place theevent handlers for these events in the global.asmx file.) In addition, you'llwant to look into different ways of managing state (in-process vs. out ofprocess). Managing session state is much simpler in ASP.NET than it was in ASPclassic, but it still requires careful study and investigation.

The project referenced in thisarticle is available for download.

 

Ken Getz isa senior consultant with MCW Technologies and splits his time betweenprogramming, writing, and training. He specializes in tools and applicationswritten in Visual Studio .NET and Visual Basic, and he is co-author of Access 2002 Developer'sHandbook Desktop Editionas well as the training materials for AppDev's ASP.NET, Access 97 and 2000,Visual Basic 5.0, and Visual Basic 6.0 classes. He speaks frequently attechnical conferences and is a contributing writer for asp.netPRO.E-mail Ken at mailto:[email protected].

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like