SessionStateUtility クラス
アセンブリ: System.Web (system.web.dll 内)


SessionStateUtility クラスは、セッション状態モジュールまたはセッション状態ストア プロバイダが使用する静的なヘルパー メソッドを提供します。アプリケーションの開発者は、コードからこのメソッドを呼び出す必要はありません。
次の表に、セッション状態モジュールとセッション状態ストア プロバイダがこのメソッドを使用する方法を示します。
GetHttpSessionStateFromContext メソッド | 既存のセッションのセッション情報を取得するか、または新しいセッションのセッション情報を作成するためにカスタムのセッション状態モジュールが使用します。 |
AddHttpSessionStateToContext メソッド | セッション データを現在の HttpContext に追加し、Session プロパティを使用してアプリケーション コードで使用できるようにするために、セッション状態モジュールによって呼び出されます。 |
RemoveHttpSessionStateFromContext メソッド | 要求の最後の ReleaseRequestState イベントまたは EndRequest イベントの発生中に、現在の HttpContext のセッション データをクリアするためにセッション状態モジュールによって呼び出されます。 |
GetSessionStaticObjects メソッド | Global.asax ファイルに定義されているオブジェクトに基づいて StaticObjects コレクションへの参照を取得するために、セッション状態モジュールによって呼び出されます。返される HttpStaticObjectsCollection コレクションには、現在の HttpContext に追加されたセッション データが含まれます。 |
セッション データは、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>


System.Web.SessionState.SessionStateUtility


Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


SessionStateUtility メソッド

名前 | 説明 | |
---|---|---|
![]() | AddHttpSessionStateToContext | 現在の要求のコンテキストにセッション データを適用します。 |
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。) |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。) |
![]() | GetHttpSessionStateFromContext | 現在の要求のコンテキストからセッション データを取得します。 |
![]() | GetSessionStaticObjects | 指定されたコンテキストの静的オブジェクトのコレクションへの参照を取得します。 |
![]() | GetType | 現在のインスタンスの Type を取得します。 ( Object から継承されます。) |
![]() | RaiseSessionEnd | ASP.NET アプリケーションの Global.asax ファイルに定義されている Session_OnEnd イベントを実行します。 |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。) |
![]() | RemoveHttpSessionStateFromContext | 指定されたコンテキストからセッション データを削除します。 |
![]() | ToString | 現在の Object を表す String を返します。 ( Object から継承されます。) |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 ( Object から継承されます。) |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 ( Object から継承されます。) |

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

名前 | 説明 | |
---|---|---|
![]() | AddHttpSessionStateToContext | 現在の要求のコンテキストにセッション データを適用します。 |
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。) |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。) |
![]() | GetHttpSessionStateFromContext | 現在の要求のコンテキストからセッション データを取得します。 |
![]() | GetSessionStaticObjects | 指定されたコンテキストの静的オブジェクトのコレクションへの参照を取得します。 |
![]() | GetType | 現在のインスタンスの Type を取得します。 (Object から継承されます。) |
![]() | RaiseSessionEnd | ASP.NET アプリケーションの Global.asax ファイルに定義されている Session_OnEnd イベントを実行します。 |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。) |
![]() | RemoveHttpSessionStateFromContext | 指定されたコンテキストからセッション データを削除します。 |
![]() | ToString | 現在の Object を表す String を返します。 (Object から継承されます。) |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。) |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 (Object から継承されます。) |

- SessionStateUtilityのページへのリンク