DekGenius.com
[ Team LiB ] Previous Section Next Section

Chapter 19. The HttpSessionState Class

A significant challenge for any Web-based application is managing user state. Unlike rich client applications, in which user state can be stored in persistent variables local to the client application, web browsers do not have a comparable built-in facility for persistently storing user state locally. This is because HTTP, the basic communication protocol used in web applications, is essentially a connectionless protocol (the HTTP specification allows persistent connections, but problems with persistent HTTP connections prevent this specification from being widely used). Each HTTP request/response is treated as completely separate from every other request/response. As such, any local variable storage cannot be reliably mapped from the request/response in which they were created to any subsequent request/response.

An early solution to this challenge was the creation of cookies, which are bits of text that are stored either in memory (per-session cookies) or on disk (persistent cookies) and are associated with the domain name from which they originated. This solves the problem of being able to associate a bit of data with more than one request/response, but it has limitations that made it a less than ideal solution:

  • Cookies can only store text (or a textual representation of other data), which means that cookie data cannot be made typesafe.

  • Cookies are limited in size (the size limit depends on the browser, but is often 4k).

  • Cookies can be manipulated on the client. If an application relying on cookies for user state does not take this into account, it is possible that a malicious user could use a manipulated cookie to breach the security of the application.

  • Most browsers allow users to turn off or refuse cookies. If users do so, an application that relies on cookies for storing user state may not function correctly.

  • Cookies present a potential performance and scalability problem, since all cookies for a given domain are sent with each request/response cycle. This means that sites making substantial use of cookies for state management will send a lot of information over the wire with each request/response cycle, whether that information is needed for that request/response or not.

For these reasons, classic ASP implemented state management through the Session intrinsic object, which provided a collection of key/value pairs for each user for storing user-specific state in memory on the web server. In classic ASP, each user session was identified by a unique identifier called the SessionID, which was sent as a per-session cookie. This alleviated several concerns of using cookies alone for storing user state, including the performance/scalability issue and cookie size limits. However, it still failed to address some issues, including the problem of users who disable cookies. ASP.NET addresses this issue by allowing both cookie-based and cookieless sessions, which are configurable at the application level.

The HttpSessionState class is ASP.NET's replacement for classic ASP's Session intrinsic object. Like the other classes that replace ASP intrinsics, HttpSessionState is exposed as a property of the Page class—in this case, the Session property. Since each ASP.NET page inherits from the Page class, these properties are available to any code in the page. This means that migrating classic ASP code that uses the Session object should be relatively painless.

The HttpSessionState class is used primarily for storing and accessing data that is shared across all the pages accessed by a particular user during a given session of interacting with the application. The HttpSessionState class provides properties and methods that map to the properties, methods, and collections of the classic ASP Session object for backward compatibility. It also adds a number of new properties and methods that increase the convenience of dealing with session state.

As in classic ASP, each user session in ASP.NET is identified by a unique SessionID, which is created at the same time as the user's session, is exposed as a property of the HttpSessionState class. In most cases, developers do not need to concern themselves with this SessionID, since ASP.NET handles it transparently.

A new SessionID is created the first time a user who does not have a current session accesses a page within an ASP.NET application whose session state has not been disabled by setting the enableSessionState attribute of the @ Page directive to False. If the page stores information in the Session collection, or if an event handler is defined for the Session.Start event in the global.asax file, then a new session is created and the newly created SessionID is assigned to that session. This delayed creation of the session until it is actually used helps conserve the limited resources of the web server and can help improve the scalability of ASP.NET applications.

When the session is created, the Session.Start event is fired. This event can be handled by creating an event handler in the global.asax file (the ASP.NET equivalent of global.asa) with the following signature:

Sub Session_OnStart( )
   'Session initialization code
End Sub

By default, the lifetime of the session for a given user is 20 minutes from the time of the user's last request. This setting is configurable at the application level via the ASP.NET web.config configuration file or at the machine level via the machine.config configuration file. Refer to Chapter 20 for more information on configuring the session timeout value. When a session ends, either by exceeding the timeout value or by code that calls the Session.Abandon method, the Session.End event is fired. Like the Start event, you can handle this event by adding an event handler to global.asax with the following signature:

Sub Session_OnEnd( )
   'Session cleanup code
End Sub

Note that the session does not end automatically when the user closes their browser, so if you want to explicitly end the session when a user is finished, you should implement some kind of logout feature that calls the Session.Abandon method.

In ASP.NET, session state is managed through the SessionStateModule class, which is an HttpModule. HttpModules are classes that derive from IHttpModule and that participate in each HTTP request in an ASP.NET application. The SessionStateModule class is responsible for generating and/or retrieving SessionIDs, firing the Start and End events of the Session object, and abstracting the underlying Session store from the HttpSessionState class.

Session state configuration is handled through the sessionState configuration section of the machine.config and web.config configuration files. (The sessionState configuration section of the web.config configuration file will be discussed in detail in Chapter 20.) The machine.config file contains the default settings for all applications on the machine, and may be overridden by adding a sessionState section to the web.config file for an application. If no sessionState section appears in the application-level configuration file, the defaults in machine.config are inherited by the application. As installed, machine.config enables in-process session state by using cookies to track the SessionID by default.

ASP.NET adds two new configuration options in addition to the timeout value and enabling/disabling of sessions that were configurable in classic ASP. The first provides built-in support for cookieless sessions. Cookieless sessions are configured in the web.config (or machine.config) file and implemented through the SessionStateModule class, which automatically modifies all relative URLs in the application and embeds the SessionID, allowing the application to maintain user state without using cookies. ASP.NET also provides the Response.ApplyAppPathModifier method, which can create absolute URLs containing the embedded SessionID given a virtual path to a resource. This allows even applications to take advantage of cookieless sessions by using absolute URLs.

The second new configuration option allows session state in ASP.NET to span multiple servers through new out-of-process storage options. ASP.NET state can now be stored in-process (the same as classic ASP), in a special ASP.NET state NT service, or in a SQL Server database. The latter two options allow multiple machines to use the same state storage facility, albeit at the expense of making out-of-process calls to set and retrieve state information. More importantly, all storage options are transparent to the developer. Information is added to and retrieved from the session state store in exactly the same fashion, regardless of which underlying session state store is used. This allows applications to be developed by initially using in-process state storage for the best performance, and later moved to out-of process storage to facilitate scaling out by adding more web servers—all without changing a single line of code in the application.

Items can be stored in the Session collection in one of three ways:

  • By calling the Add method, passing in the name to assign to the item and the item's value. This value can be of any type supported by the CLR, including object instances, which are automatically serialized before being stored. The Add method takes the form:

    Session.Add(itemName, itemValue)
  • By explicitly referring to the Item property, passing a name or index to assign to the new item:

    Session.Item(itemName) = itemValue
  • By implicitly referring to the Item property, passing a name to assign to the new item. This was the most common technique used in classic ASP.

    Session(itemName) = itemValue

Items in the Session collection can be accessed in one of three ways:

  • By retrieving and iterating over the collection of keys in the Session collection (see the Keys collection description for an example).

  • By explicitly referring to the Item property, passing the name of the item to retrieve:

    localVar = Session.Item(itemName)
  • By implicitly referring to the Item property, passing the name of the item to retrieve. This was the most common technique used in classic ASP:

    localVar = Session(itemName)

Items can be removed from the Session collection in one of several ways:

  • By calling the Clear method (clears all items).

  • By calling the RemoveAll method (removes all items, which is effectively the same as calling the Clear method).

  • By calling the Remove method, passing the name of the item to remove.

  • By calling the RemoveAt method, passing the index of the item to remove.

Table 19-1 lists the properties, collections, methods, and events exposed by the HttpSessionState class.

Table 19-1. HttpSessionState class summary

Properties

Collections

Methods (public instance)

Events[1]

CodePage

Contents

Abandon

Start

Count

Keys

Add

End

IsCookieless

StaticObjects

Clear

 

IsNewSession

 

CopyTo

 

IsReadOnly

 

Remove

 

Item

 

RemoveAll

 

LCID

 

RemoveAt

 

Mode

   

SessionID

   

Timeout

   

[1] These events are exposed by the SessionStateModule class, rather than the HttpSessionState class.

    [ Team LiB ] Previous Section Next Section