SessionStateUtility クラスとは? わかりやすく解説

SessionStateUtility クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

ASP.NET アプリケーションセッション情報管理するために、セッション状態モジュールセッション状態ストア プロバイダによって使用されるヘルパー メソッド提供します。このクラス継承できません。

名前空間: System.Web.SessionState
アセンブリ: System.Web (system.web.dll 内)
構文構文

Public NotInheritable Class
 SessionStateUtility
public static class SessionStateUtility
public ref class SessionStateUtility abstract
 sealed
public final class SessionStateUtility
public final class SessionStateUtility
解説解説

SessionStateUtility クラスは、セッション状態モジュールまたはセッション状態ストア プロバイダ使用する静的ヘルパー メソッド提供しますアプリケーション開発者は、コードからこのメソッド呼び出す必要はありません。

次の表に、セッション状態モジュールセッション状態ストア プロバイダがこのメソッド使用する方法示します

セッション データは、HttpSessionStateContainer オブジェクトまたは有効な IHttpSessionState インターフェイス実装として、現在の HttpContext渡されるか、またはそこから取得されます。

セッション状態ストア プロバイダ実装の詳細については、「セッション状態ストア プロバイダ実装」を参照してください

使用例使用例

Hashtable使用してセッション情報メモリ保存するカスタムセッション状態モジュール実装コード例次に示します。このモジュールは、SessionStateUtility クラス使用して現在の HttpContext と SessionIDManager を参照し現在の HttpStaticObjectsCollection取得してASP.NET アプリケーションの Global.asax ファイル定義されている Session_OnEnd イベント生成します。このアプリケーションでは、同時に発生する Web 要求が同じセッション識別子使用できます

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
  
    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 pSessionID        As String
              
    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 pSessionData As SessionItem 

    Class SessionItem
      Friend Items         As SessionStateItemCollection
      Friend StaticObjects As HttpStaticObjectsCollection
 
      Friend Expires       As DateTime
    End Class


    '
    ' IHttpModule.Init
    '

    Public Sub Init(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)

      ' Get a reference to the SessionIDManager for the current HttpApplication.
      pSessionIDManager = new SessionIDManager()
      PSessioNIDManager.Initialize()

      ' If not already initialized, initialize timer and configuration.
      If Not pInitialized Then
        SyncLock Me
          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
      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(state As Object)
      Try
        pHashtableLock.AcquireWriterLock(Int32.MaxValue)

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

          If item.Expires <= DateTime.Now Then
                     
            pSessionItems.Remove(enTry.Key)

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

            SessionStateUtility.RaiseSessionEnd(stateProvider, Me,
 EventArgs.Empty)
          End If
        Next
      Finally
        pHashtableLock.ReleaseWriterLock()
      End Try
    End Sub


    '
    ' Event handler for HttpApplication.AcquireRequestState
    '

    Private Sub OnAcquireRequestState(source
 As Object, args As EventArgs)
      Dim app     As HttpApplication = CType(source,
 HttpApplication)
      Dim context As HttpContext     = app.Context
      Dim isNew   As Boolean
         = False

      pSessionData = Nothing

      pSessionID = pSessionIDManager.GetSessionID(context)
      
      If Not pSessionID Is
 Nothing Then      
        Try
          pHashtableLock.AcquireReaderLock(Int32.MaxValue)
          pSessionData = CType(pSessionItems(pSessionID), SessionItem)

          If Not pSessionData Is
 Nothing Then _
            pSessionData.Expires = DateTime.Now.AddMinutes(pTimeout)
        Finally
          pHashtableLock.ReleaseReaderLock()
        End Try
      Else
        Dim redirected, cookieAdded As Boolean

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

        If redirected Then Return
      End If

      If pSessionData 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

        pSessionData = New SessionItem()

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

        Try
          pHashtableLock.AcquireWriterLock(Int32.MaxValue)
          pSessionItems(pSessionID) = pSessionData
        Finally
          pHashtableLock.ReleaseWriterLock()
        End Try
      End If
            
      ' Add the session data to the current HttpContext.
      SessionStateUtility.AddHttpSessionStateToContext(context, _
                       New HttpSessionStateContainer(pSessionID,
 _
                                                    pSessionData.Items, _
                                                    pSessionData.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(source
 As Object, args As EventArgs)
      Dim app     As HttpApplication = CType(source,
 HttpApplication)
      Dim context As HttpContext     = app.Context

      ' 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)
          pSessionItems.Remove(pSessionID)
        Finally
          pHashtableLock.ReleaseWriterLock()
        End Try

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

      SessionStateUtility.RemoveHttpSessionStateFromContext(context)
    End Sub

  End Class
End Namespace
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
  {
    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 string              pSessionID;
    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 SessionItem pSessionData;

    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)
        ((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);

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

          if (item.Expires <= DateTime.Now)
          {           
            pSessionItems.Remove(entry.Key);

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

            SessionStateUtility.RaiseSessionEnd(stateProvider, this,
 EventArgs.Empty);
          }
        }
      }
      finally
      {
        pHashtableLock.ReleaseWriterLock();
      }
    }


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

    private void OnAcquireRequestState(object
 source, EventArgs args)
    {
      HttpApplication app     = (HttpApplication)source;
      HttpContext     context = app.Context;
      bool            isNew   = false;

      pSessionData = null;

      pSessionID = pSessionIDManager.GetSessionID(context);
      
      if (pSessionID != null)
      {
        try
        {
          pHashtableLock.AcquireReaderLock(Int32.MaxValue);
          pSessionData = (SessionItem)pSessionItems[pSessionID];

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

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

        if (redirected)
          return;
      }

      if (pSessionData == null)
      {
        // Identify the session as a new session state instance. Create
 a new SessionItem
        // and add it to the local Hashtable.

        isNew = true;

        pSessionData = new SessionItem();

        pSessionData.Items         = new SessionStateItemCollection();
        pSessionData.StaticObjects = SessionStateUtility.GetSessionStaticObjects(context);
        pSessionData.Expires       = DateTime.Now.AddMinutes(pTimeout);

        try
        {
          pHashtableLock.AcquireWriterLock(Int32.MaxValue);
          pSessionItems[pSessionID] = pSessionData;
        }
        finally
        {
          pHashtableLock.ReleaseWriterLock();
        }
      }
            
      // Add the session data to the current HttpContext.
      SessionStateUtility.AddHttpSessionStateToContext(context,
                       new HttpSessionStateContainer(pSessionID
,
                                                    pSessionData.Items,
                                                    pSessionData.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;

      // 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);
          pSessionItems.Remove(pSessionID);
        }
        finally
        {
          pHashtableLock.ReleaseWriterLock();
        }

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

      SessionStateUtility.RemoveHttpSessionStateFromContext(context);
    }

  }
}

ASP.NET アプリケーションでこのカスタムセッション状態モジュール使用するには、次の例のように Web.config ファイル既存の SessionStateModule 参照置き換えます

<configuration>
  <system.web>
    <httpModules>
      <remove name="Session" />
      <add name="Session"
      type="Samples.AspNet.SessionState.MySessionStateModule" />
    </httpModules>
  </system.web>
</configuration>
.NET Framework のセキュリティ.NET Frameworkセキュリティ
継承階層継承階層
System.Object
  System.Web.SessionState.SessionStateUtility
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「SessionStateUtility クラス」の関連用語

SessionStateUtility クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



SessionStateUtility クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS