SessionStateUtility SessionStateUtility SessionStateUtility SessionStateUtility Class

Definition

Stellt von Sitzungszustandmodulen verwendete Hilfsmethoden und Sitzungszustandanbieter zum Verwalten der Sitzungsinformationen für eine ASP.NET-Anwendung bereit.Provides helper methods used by session-state modules and session-state store providers to manage session information for an ASP.NET application. Diese Klasse kann nicht vererbt werden.This class cannot be inherited.

public ref class SessionStateUtility abstract sealed
public static class SessionStateUtility
type SessionStateUtility = class
Public Class SessionStateUtility
Vererbung
SessionStateUtilitySessionStateUtilitySessionStateUtilitySessionStateUtility

Beispiele

Das folgende Codebeispiel zeigt eine benutzerdefinierte Implementierung des Sitzungs Zustands Moduls, die Sitzungsinformationen im Arbeitsspeicher Hashtableunter Verwendung eines speichert.The following code example shows a custom session-state module implementation that stores session information in memory using a Hashtable. Das Modul verwendet die SessionStateUtility -Klasse, um auf HttpContext den SessionIDManageraktuellen und, die HttpStaticObjectsCollectionaktuelle-Klasse und das Session_OnEnd -Ereignis zu verweisen, das in der Datei Global. asax für die ASP.NET-Anwendung definiert ist.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. Diese Anwendung verhindert nicht, dass gleichzeitige Webanforderungen denselben Sitzungs Bezeichner verwenden.This application does not prevent simultaneous Web requests from using the same session identifier.

using System;
using System.Web;
using System.Web.SessionState;
using System.Collections;
using System.Threading;
using System.Web.Configuration;
using System.Configuration;

namespace Samples.AspNet.SessionState
{

    public sealed class MySessionStateModule : IHttpModule, IDisposable
    {
        private Hashtable pSessionItems = new Hashtable();
        private Timer pTimer;
        private int pTimerSeconds = 10;
        private bool pInitialized = false;
        private int pTimeout;
        private HttpCookieMode pCookieMode = HttpCookieMode.UseCookies;
        private ReaderWriterLock pHashtableLock = new ReaderWriterLock();
        private ISessionIDManager pSessionIDManager;
        private SessionStateSection pConfig;


        // 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
        {
            internal SessionStateItemCollection Items;
            internal HttpStaticObjectsCollection StaticObjects;
            internal DateTime Expires;
        }


        //
        // IHttpModule.Init
        //

        public void Init(HttpApplication app)
        {
            // Add event handlers.
            app.AcquireRequestState += new EventHandler(this.OnAcquireRequestState);
            app.ReleaseRequestState += new EventHandler(this.OnReleaseRequestState);

            // Create a SessionIDManager.
            pSessionIDManager = new SessionIDManager();
            pSessionIDManager.Initialize();

            // If not already initialized, initialize timer and configuration.
            if (!pInitialized)
            {
                lock (typeof(MySessionStateModule))
                {
                    if (!pInitialized)
                    {
                        // Create a Timer to invoke the ExpireCallback method based on
                        // the pTimerSeconds value (e.g. every 10 seconds).

                        pTimer = new Timer(new TimerCallback(this.ExpireCallback),
                                           null,
                                           0,
                                           pTimerSeconds * 1000);

                        // Get the configuration section and set timeout and CookieMode values.
                        Configuration cfg =
                          WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
                        pConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");

                        pTimeout = (int)pConfig.Timeout.TotalMinutes;
                        pCookieMode = pConfig.Cookieless;

                        pInitialized = true;
                    }
                }
            }
        }



        //
        // IHttpModule.Dispose
        //

        public void Dispose()
        {
            if (pTimer != null)
            {
                this.pTimer.Dispose();
               ((IDisposable)pTimer).Dispose();
            }
        }


        //
        // Called periodically by the Timer created in the Init method to check for 
        // expired sessions and remove expired data.
        //

        void ExpireCallback(object state)
        {
            try
            {
                pHashtableLock.AcquireWriterLock(Int32.MaxValue);

                this.RemoveExpiredSessionData();

            }
            finally
            {
                pHashtableLock.ReleaseWriterLock();
            }
        }


        //
        // Recursivly remove expired session data from session collection.
        //
        private void RemoveExpiredSessionData()
        {
            string sessionID;

            foreach (DictionaryEntry entry in pSessionItems)
            {
                SessionItem item = (SessionItem)entry.Value;

                if ( DateTime.Compare(item.Expires, DateTime.Now)<=0 )
                {
                    sessionID = entry.Key.ToString();
                    pSessionItems.Remove(entry.Key);

                    HttpSessionStateContainer stateProvider =
                      new HttpSessionStateContainer(sessionID,
                                                   item.Items,
                                                   item.StaticObjects,
                                                   pTimeout,
                                                   false,
                                                   pCookieMode,
                                                   SessionStateMode.Custom,
                                                   false);

                    SessionStateUtility.RaiseSessionEnd(stateProvider, this, EventArgs.Empty);
                    this.RemoveExpiredSessionData();
                    break;
                }
            }

        }


        //
        // Event handler for HttpApplication.AcquireRequestState
        //

        private void OnAcquireRequestState(object source, EventArgs args)
        {
            HttpApplication app = (HttpApplication)source;
            HttpContext context = app.Context;
            bool isNew = false;
            string sessionID;
            SessionItem sessionData = null;
            bool supportSessionIDReissue = true;

            pSessionIDManager.InitializeRequest(context, false, out supportSessionIDReissue);
            sessionID = pSessionIDManager.GetSessionID(context);


            if (sessionID != null)
            {
                try
                {
                    pHashtableLock.AcquireReaderLock(Int32.MaxValue);
                    sessionData = (SessionItem)pSessionItems[sessionID];

                    if (sessionData != null)
                       sessionData.Expires = DateTime.Now.AddMinutes(pTimeout);
                }
                finally
                {
                    pHashtableLock.ReleaseReaderLock();
                }
            }
            else
            {
                bool redirected, cookieAdded;

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

                if (redirected)
                    return;
            }

            if (sessionData == null)
            {
                // 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);

                try
                {
                    pHashtableLock.AcquireWriterLock(Int32.MaxValue);
                    pSessionItems[sessionID] = sessionData;
                }
                finally
                {
                    pHashtableLock.ReleaseWriterLock();
                }
            }

            // Add the session data to the current HttpContext.
            SessionStateUtility.AddHttpSessionStateToContext(context,
                             new HttpSessionStateContainer(sessionID,
                                                          sessionData.Items,
                                                          sessionData.StaticObjects,
                                                          pTimeout,
                                                          isNew,
                                                          pCookieMode,
                                                          SessionStateMode.Custom,
                                                          false));

            // Execute the Session_OnStart event for a new session.
            if (isNew && Start != null)
            {
                Start(this, EventArgs.Empty);
            }
        }

        //
        // Event for Session_OnStart event in the Global.asax file.
        //

        public event EventHandler Start;


        //
        // Event handler for HttpApplication.ReleaseRequestState
        //

        private void OnReleaseRequestState(object source, EventArgs args)
        {
            HttpApplication app = (HttpApplication)source;
            HttpContext context = app.Context;
            string sessionID;

            // Read the session state from the context
            HttpSessionStateContainer stateProvider =
              (HttpSessionStateContainer)(SessionStateUtility.GetHttpSessionStateFromContext(context));

            // 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)
            {
                try
                {
                    pHashtableLock.AcquireWriterLock(Int32.MaxValue);

                    sessionID = pSessionIDManager.GetSessionID(context);
                    pSessionItems.Remove(sessionID);
                }
                finally
                {
                    pHashtableLock.ReleaseWriterLock();
                }

                SessionStateUtility.RaiseSessionEnd(stateProvider, this, EventArgs.Empty);
            }

            SessionStateUtility.RemoveHttpSessionStateFromContext(context);
        }


    }
}
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()
            pSessionIDManager.Initialize()

            ' 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( _
                            System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath)
                        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)
            Try
                pHashtableLock.AcquireWriterLock(Int32.MaxValue)

                Me.RemoveExpiredSessionData()

            Finally
                pHashtableLock.ReleaseWriterLock()
            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()
                    pSessionItems.Remove(entry.Key)

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

                    SessionStateUtility.RaiseSessionEnd(stateProvider, Me, EventArgs.Empty)
                    Me.RemoveExpiredSessionData()
                    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
                Try
                    pHashtableLock.AcquireReaderLock(Int32.MaxValue)
                    sessionData = CType(pSessionItems(sessionID), SessionItem)

                    If Not (sessionData Is Nothing) Then
                        sessionData.Expires = DateTime.Now.AddMinutes(pTimeout)
                    End If
                Finally
                    pHashtableLock.ReleaseReaderLock()
                End Try
            Else
                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)

                Try
                    pHashtableLock.AcquireWriterLock(Int32.MaxValue)
                    pSessionItems(sessionID) = sessionData
                Finally
                    pHashtableLock.ReleaseWriterLock()
                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, _
                                                          False))

            ' 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
                Try
                    pHashtableLock.AcquireWriterLock(Int32.MaxValue)

                    sessionID = pSessionIDManager.GetSessionID(context)
                    pSessionItems.Remove(sessionID)
                Finally
                    pHashtableLock.ReleaseWriterLock()
                End Try

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

          SessionStateUtility.RemoveHttpSessionStateFromContext(context)
        End Sub
    
    End Class
End Namespace

Wenn Sie dieses benutzerdefinierte Sitzungs Zustands Modul in einer ASP.NET-Anwendung verwenden möchten, können Sie SessionStateModule den vorhandenen Verweis in der Datei "Web. config" ersetzen, wie im folgenden Beispiel gezeigt.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.

<configuration>  
  <system.web>  
    <httpModules>  
      <remove name="Session" />  
      <add name="Session"  
      type="Samples.AspNet.SessionState.MySessionStateModule" />  
    </httpModules>  
  </system.web>  
</configuration>  

Hinweise

Die SessionStateUtility -Klasse stellt statische Hilfsmethoden bereit, die von einem Sitzungs Zustands Modul oder einem Sitzungs Zustands Speicher-Anbieter verwendet werden.The SessionStateUtility class provides static helper methods that are used by a session-state module or a session-state store provider. Anwendungsentwickler müssen diese Methoden nicht aus Ihrem Code abrufen.Application developers will not need to call these methods from their code.

In der folgenden Tabelle wird beschrieben, wie das Sitzungs Zustands Modul und der Sitzungs Zustands Speicher-Anbieter die-Methoden verwenden.The following table describes the ways the session-state module and session-state store provider use the methods.

MethodeMethod VerwendungUse
GetHttpSessionStateFromContext-MethodeGetHttpSessionStateFromContext method Kann von benutzerdefinierten Sitzungs Zustands Modulen verwendet werden, um entweder Sitzungsinformationen für eine vorhandene Sitzung abzurufen oder Sitzungsinformationen für eine neue Sitzung zu erstellen.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-MethodeAddHttpSessionStateToContext method Wird vom Sitzungs Zustands Modul aufgerufen, um die Sitzungsdaten dem aktuellen HttpContext hinzuzufügen und für den Anwendungscode über die Session -Eigenschaft verfügbar zu machen.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-MethodeRemoveHttpSessionStateFromContext method Wird vom Sitzungs Zustands Modul während der ReleaseRequestState -oder EndRequest -Ereignisse am Ende einer Anforderung aufgerufen, um Sitzungsdaten aus der aktuellen HttpContextzu löschen.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-MethodeGetSessionStaticObjects method Wird vom Sitzungs Zustands Modul aufgerufen, um einen Verweis auf die Auflistung StaticObjects auf der Grundlage der in der Datei Global. asax definierten Objekte zu erhalten.Called by the session-state module to get a reference to the StaticObjects collection based on objects defined in the Global.asax file. Die HttpStaticObjectsCollection zurückgegebene Auflistung ist in den Sitzungsdaten enthalten, die der HttpContextaktuellen hinzugefügt werden.The HttpStaticObjectsCollection collection returned is included with the session data added to the current HttpContext.

Sitzungsdaten werden an das aktuelle- HttpContext HttpSessionStateContainer Objekt oder an IHttpSessionState eine beliebige gültige Implementierung der-Schnittstelle an die aktuelle-Schnittstelle und abgerufen.Session data is passed to and retrieved from the current HttpContext as an HttpSessionStateContainer object or any valid implementation of the IHttpSessionState interface.

Weitere Informationen zum Implementieren eines Sitzungs Zustands Speicher-Anbieters finden Sie unter Implementieren eines Sitzungs Zustands Speicher-Anbieters.For information about implementing a session-state store provider, see Implementing a Session-State Store Provider.

Eigenschaften

SerializationSurrogateSelector SerializationSurrogateSelector SerializationSurrogateSelector SerializationSurrogateSelector

Ruft eine Serialisierungsersatzauswahl ab oder legt diese fest, die für die Anpassung der Sitzungsserialisierung verwendet wird.Gets or sets a serialization surrogate selector that is used for session serialization customization.

Methoden

AddHttpSessionStateToContext(HttpContext, IHttpSessionState) AddHttpSessionStateToContext(HttpContext, IHttpSessionState) AddHttpSessionStateToContext(HttpContext, IHttpSessionState) AddHttpSessionStateToContext(HttpContext, IHttpSessionState)

Wendet die Sitzungsdaten auf den Kontext für die aktuelle Anforderung an.Applies the session data to the context for the current request.

GetHttpSessionStateFromContext(HttpContext) GetHttpSessionStateFromContext(HttpContext) GetHttpSessionStateFromContext(HttpContext) GetHttpSessionStateFromContext(HttpContext)

Ruft Sitzungsdaten für die aktuelle Anforderung vom Kontext ab.Retrieves session data from the context for the current request.

GetSessionStaticObjects(HttpContext) GetSessionStaticObjects(HttpContext) GetSessionStaticObjects(HttpContext) GetSessionStaticObjects(HttpContext)

Ruft einen Verweis auf die Auflistung der statischen Objekte für den angegebenen Kontext ab.Gets a reference to the static objects collection for the specified context.

IsSessionStateReadOnly(HttpContext) IsSessionStateReadOnly(HttpContext) IsSessionStateReadOnly(HttpContext) IsSessionStateReadOnly(HttpContext)

Ruft einen Wert ab, der angibt, ob der Sitzungszustand für den angegebenen HttpContext schreibgeschützt ist.Gets a value which indicates whether the session state is read-only for the specified HttpContext.

IsSessionStateRequired(HttpContext) IsSessionStateRequired(HttpContext) IsSessionStateRequired(HttpContext) IsSessionStateRequired(HttpContext)

Ruft einen Wert ab, der angibt, ob der Sitzungszustand für den angegebenen HttpContext erforderlich ist.Gets a value which indicates whether the session state is required for the specified HttpContext.

RaiseSessionEnd(IHttpSessionState, Object, EventArgs) RaiseSessionEnd(IHttpSessionState, Object, EventArgs) RaiseSessionEnd(IHttpSessionState, Object, EventArgs) RaiseSessionEnd(IHttpSessionState, Object, EventArgs)

Führt das in der Datei Global.asax für die ASP.NET-Anwendung definierte Session_OnEnd-Ereignis aus.Executes the Session_OnEnd event defined in the Global.asax file for the ASP.NET application.

RemoveHttpSessionStateFromContext(HttpContext) RemoveHttpSessionStateFromContext(HttpContext) RemoveHttpSessionStateFromContext(HttpContext) RemoveHttpSessionStateFromContext(HttpContext)

Entfernt Sitzungsdaten aus dem angegebenen Kontext.Removes session data from the specified context.

Gilt für:

Siehe auch