Share via


SessionStateUtility 클래스

정의

ASP.NET 애플리케이션에 대한 세션 정보를 관리하기 위해 세션 상태 모듈 및 세션 상태 저장소 공급자가 사용하는 도우미 메서드를 제공합니다. 이 클래스는 상속될 수 없습니다.

public ref class SessionStateUtility abstract sealed
public static class SessionStateUtility
type SessionStateUtility = class
Public Class SessionStateUtility
상속
SessionStateUtility

예제

다음 코드 예제에서는 를 사용 하 여 메모리에 세션 정보를 저장 하는 사용자 지정 세션 상태 모듈 구현을 보여줍니다 Hashtable. 모듈을 사용 합니다 SessionStateUtility 현재 참조 하는 클래스 HttpContextSessionIDManager, 현재 검색 HttpStaticObjectsCollection, 시키고를 Session_OnEnd ASP.NET에 대 한 Global.asax 파일에 정의 된 이벤트 애플리케이션입니다. 이 애플리케이션에서 동일한 세션 식별자를 사용 하 여 동시 웹 요청을 방지 하지 않습니다.

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

ASP.NET 애플리케이션에서이 사용자 지정 세션 상태 모듈을 사용 하려면 바꾸면 기존 SessionStateModule 다음 예와에서 같이 Web.config 파일에서 참조 합니다.

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

설명

클래스는 SessionStateUtility 세션 상태 모듈 또는 세션 상태 저장소 공급자에서 사용하는 정적 도우미 메서드를 제공합니다. 애플리케이션 개발자는 코드에서 이러한 메서드를 호출할 필요가 없습니다.

다음 표에서는 세션 상태 모듈 및 세션 상태 저장소 공급자가 메서드를 사용하는 방법을 설명합니다.

메서드 Windows Server Update Services와 함께
GetHttpSessionStateFromContext 메서드 사용자 지정 세션 상태 모듈에서 기존 세션에 대한 세션 정보를 검색하거나 새 세션에 대한 세션 정보를 만드는 데 사용할 수 있습니다.
AddHttpSessionStateToContext 메서드 현재 세션 데이터를 추가 하려면 세션 상태 모듈에 의해 호출 HttpContext 를 통해 애플리케이션 코드에 사용할 수 있도록 하 고는 Session 속성입니다.
RemoveHttpSessionStateFromContext 메서드 현재 에서 세션 데이터를 지우기 위해 요청이 끝날 때 또는 이벤트 중에 ReleaseRequestState 세션 상태 모듈에서 호출됩니다HttpContext.EndRequest
GetSessionStaticObjects 메서드 Global.asax 파일에 정의된 개체를 기반으로 컬렉션에 대한 참조를 가져오기 위해 StaticObjects 세션 상태 모듈에서 호출됩니다. HttpStaticObjectsCollection 반환된 컬렉션은 현재 HttpContext에 추가된 세션 데이터에 포함됩니다.

세션 데이터는 에 전달되고 현재 HttpContext 에서 개체 또는 인터페이스의 IHttpSessionState 유효한 구현으로 HttpSessionStateContainer 검색됩니다.

세션 상태 저장소 공급자를 구현하는 방법에 대한 자세한 내용은 Session-State 스토어 공급자 구현을 참조하세요.

속성

SerializationSurrogateSelector

세션 serialization 사용자 지정에 사용하는 serialization 서로게이트 선택기를 가져오거나 설정합니다.

메서드

AddHttpSessionStateToContext(HttpContext, IHttpSessionState)

현재 요청의 컨텍스트에 세션 데이터를 적용합니다.

GetHttpSessionStateFromContext(HttpContext)

현재 요청의 컨텍스트에서 세션 데이터를 검색합니다.

GetSessionStaticObjects(HttpContext)

지정된 컨텍스트의 정적 개체 컬렉션에 대한 참조를 가져옵니다.

IsSessionStateReadOnly(HttpContext)

세션 상태가 지정된 HttpContext에 대해 읽기 전용인지 여부를 나타내는 값을 가져옵니다.

IsSessionStateRequired(HttpContext)

세션 상태가 지정된 HttpContext에 대해 필수인지 여부를 나타내는 값을 가져옵니다.

RaiseSessionEnd(IHttpSessionState, Object, EventArgs)

ASP.NET 애플리케이션의 Global.asax 파일에 정의된 Session_OnEnd 이벤트를 실행합니다.

RemoveHttpSessionStateFromContext(HttpContext)

지정된 컨텍스트에서 세션 데이터를 제거합니다.

적용 대상

추가 정보