This documentation is archived and is not being maintained.

SessionStateUtility Class

Provides helper methods used by session-state modules and session-state store providers to manage session information for an ASP.NET application. This class cannot be inherited.

Namespace:  System.Web.SessionState
Assembly:  System.Web (in System.Web.dll)

<AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
Public NotInheritable Class SessionStateUtility
You do not need to declare an instance of a static class in order to access its members.

The SessionStateUtility class provides static helper methods that are used by a session-state module or a session-state store provider. Application developers will not need to call these methods from their code.

The following table describes the ways the session-state module and session-state store provider use the methods.



GetHttpSessionStateFromContext method

Can be used by custom session-state modules to either retrieve session information for an existing session or create session information for a new session.

AddHttpSessionStateToContext method

Called by the session-state module to add the session data to the current HttpContext and make it available to application code through the Session property.

RemoveHttpSessionStateFromContext method

Called by the session-state module during the ReleaseRequestState or EndRequest events at the end of a request, to clear session data from the current HttpContext.

GetSessionStaticObjects method

Called by the session-state module to get a reference to the StaticObjects collection based on objects defined in the Global.asax file. The HttpStaticObjectsCollection collection returned is included with the session data added to the current HttpContext.

Session data is passed to and retrieved from the current HttpContext as an HttpSessionStateContainer object or any valid implementation of the IHttpSessionState interface.

For information about implementing a session-state store provider, see Implementing a Session-State Store Provider.

The following code example shows a custom session-state module implementation that stores session information in memory using a Hashtable. The module uses the SessionStateUtility class to reference the current HttpContext and SessionIDManager, retrieve the current HttpStaticObjectsCollection, and raise the Session_OnEnd event defined in the Global.asax file for the ASP.NET application. This application does not prevent simultaneous Web requests from using the same session identifier.

Imports System
Imports System.Web
Imports System.Web.SessionState
Imports System.Collections
Imports System.Threading
Imports System.Web.Configuration
Imports System.Configuration

Namespace Samples.AspNet.SessionState

    Public NotInheritable Class MySessionStateModule
        Implements IHttpModule, IDisposable

        Private pSessionItems As Hashtable = New Hashtable()
        Private pTimer As Timer
        Private pTimerSeconds As Integer = 10
        Private pInitialized As Boolean = False 
        Private pTimeout As Integer 
        Private pCookieMode As HttpCookieMode = HttpCookieMode.UseCookies
        Private pHashtableLock As ReaderWriterLock = New ReaderWriterLock()
        Private pSessionIDManager As ISessionIDManager
        Private pConfig As SessionStateSection

        ' The SessionItem class is used to store data for a particular session along with 
        ' an expiration date and time. SessionItem objects are added to the local Hashtable 
        ' in the OnReleaseRequestState event handler and retrieved from the local Hashtable 
        ' in the OnAcquireRequestState event handler. The ExpireCallback method is called 
        ' periodically by the local Timer to check for all expired SessionItem objects in the 
        ' local Hashtable and remove them.  
        Private Class SessionItem
            Friend Items As SessionStateItemCollection
            Friend StaticObjects As HttpStaticObjectsCollection
            Friend Expires As DateTime
        End Class 

        ' IHttpModule.Init 

	Public Sub Init(ByVal app As HttpApplication) Implements IHttpModule.Init
            ' Add event handlers. 
            AddHandler app.AcquireRequestState, New EventHandler(AddressOf Me.OnAcquireRequestState)
            AddHandler app.ReleaseRequestState, New EventHandler(AddressOf Me.OnReleaseRequestState)

            ' Create a SessionIDManager.
            pSessionIDManager = New SessionIDManager()

            ' If not already initialized, initialize timer and configuration. 
            If Not pInitialized Then
                SyncLock GetType(MySessionStateModule)
                    If Not pInitialized Then 
                        ' Create a Timer to invoke the ExpireCallback method based on 
                        ' the pTimerSeconds value (e.g. every 10 seconds).
                        pTimer = New Timer(New TimerCallback(AddressOf Me.ExpireCallback), _
                                           Nothing, _
                                           0, _
                                           pTimerSeconds * 1000)

                        ' Get the configuration section and set timeout and CookieMode values. 
                        Dim cfg As System.Configuration.Configuration = _
                          WebConfigurationManager.OpenWebConfiguration( _
                        pConfig = CType(cfg.GetSection("system.web/sessionState"), SessionStateSection)

                        pTimeout = CInt(pConfig.Timeout.TotalMinutes)
                        pCookieMode = pConfig.Cookieless

                        pInitialized = True 
                    End If 
                End SyncLock
            End If 
        End Sub 

        ' IHttpModule.Dispose 
        Public Sub Dispose() Implements IHttpModule.Dispose, IDisposable.Dispose
            If Not pTimer Is Nothing Then CType(pTimer, IDisposable).Dispose()
        End Sub 

        ' Called periodically by the Timer created in the Init method to check for  
        ' expired sessions and remove expired data. 
        Sub ExpireCallback(ByVal state As Object)


            End Try 

        End Sub 

        ' Recursivly remove expired session data from session collection. 
        Private Sub RemoveExpiredSessionData()
            Dim sessionID As String 
            Dim entry As DictionaryEntry

            For Each entry In pSessionItems
                Dim item As SessionItem = CType(entry.Value, SessionItem)

                If DateTime.Compare(item.Expires, DateTime.Now) <= 0 Then
                    sessionID = entry.Key.ToString()

                    Dim stateProvider As HttpSessionStateContainer = _
                      New HttpSessionStateContainer(sessionID, _
                                                   item.Items, _
                                                   item.StaticObjects, _
                                                   pTimeout, _
                                                   False, _
                                                   pCookieMode, _
                                                   SessionStateMode.Custom, _

                    SessionStateUtility.RaiseSessionEnd(stateProvider, Me, EventArgs.Empty)
                    Exit For 
                End If 
            Next entry
        End Sub 

        ' Event handler for HttpApplication.AcquireRequestState 
        Private Sub OnAcquireRequestState(ByVal [source] As Object, ByVal args As EventArgs)
            Dim app As HttpApplication = CType([source], HttpApplication)
            Dim context As HttpContext = app.Context
            Dim isNew As Boolean = False 
            Dim sessionID As String 
            Dim sessionData As SessionItem = Nothing 
            Dim supportSessionIDReissue As Boolean = True

            pSessionIDManager.InitializeRequest(context, False, supportSessionIDReissue)
            sessionID = pSessionIDManager.GetSessionID(context)

            If Not (sessionID Is Nothing) Then 
                    sessionData = CType(pSessionItems(sessionID), SessionItem)

                    If Not (sessionData Is Nothing) Then
                        sessionData.Expires = DateTime.Now.AddMinutes(pTimeout)
                    End If 
                End Try 
                Dim redirected, cookieAdded As Boolean

                sessionID = pSessionIDManager.CreateSessionID(context)
                pSessionIDManager.SaveSessionID(context, sessionID, redirected, cookieAdded)

                If redirected Then Return 
            End If 
            If sessionData Is Nothing Then 
                ' Identify the session as a new session state instance. Create a new SessionItem 
                ' and add it to the local Hashtable.
                isNew = True

                sessionData = New SessionItem()

                sessionData.Items = New SessionStateItemCollection()
                sessionData.StaticObjects = SessionStateUtility.GetSessionStaticObjects(context)
                sessionData.Expires = DateTime.Now.AddMinutes(pTimeout)

                    pSessionItems(sessionID) = sessionData
                End Try 
            End If 

            ' Add the session data to the current HttpContext.
            SessionStateUtility.AddHttpSessionStateToContext(context, _
                             New HttpSessionStateContainer(sessionID, _
                                                          sessionData.Items, _
                                                          sessionData.StaticObjects, _
                                                          pTimeout, _
                                                          isNew, _
                                                          pCookieMode, _
                                                          SessionStateMode.Custom, _

            ' Execute the Session_OnStart event for a new session. 
            If isNew Then RaiseEvent Start(Me, EventArgs.Empty)
        End Sub 

        ' Event for Session_OnStart event in the Global.asax file. 
	Public Event Start As EventHandler

        ' Event handler for HttpApplication.ReleaseRequestState 
        Private Sub OnReleaseRequestState(ByVal [source] As Object, ByVal args As EventArgs)
            Dim app As HttpApplication = CType([source], HttpApplication)
            Dim context As HttpContext = app.Context
            Dim sessionID As String 

            ' Read the session state from the context 
            Dim stateProvider As HttpSessionStateContainer = _
               CType(SessionStateUtility.GetHttpSessionStateFromContext(context), HttpSessionStateContainer)

            ' If Session.Abandon() was called, remove the session data from the local Hashtable 
            ' and execute the Session_OnEnd event from the Global.asax file. 
            If stateProvider.IsAbandoned Then 

                    sessionID = pSessionIDManager.GetSessionID(context)
                End Try

                SessionStateUtility.RaiseSessionEnd(stateProvider, Me, EventArgs.Empty)
            End If

        End Sub 

    End Class 
End Namespace

To use this custom session-state module in an ASP.NET application, you can replace the existing SessionStateModule reference in the Web.config file, as shown in the following example.

      <remove name="Session" />
      <add name="Session"
      type="Samples.AspNet.SessionState.MySessionStateModule" />


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0