SessionStateUtility 类
注意:此类在 .NET Framework 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 类提供会话状态模块或会话状态存储提供程序使用的静态帮助器方法,应用程序开发人员不必从代码中调用这些方法。
下表描述了会话状态模块和会话状态存储提供程序如何使用这些方法。
|
方法 |
使用 |
|---|---|
|
自定义会话状态模块可以用来检索现有会话的会话信息,或创建新会话的会话信息。 |
|
|
由会话状态模块调用,以向当前 HttpContext 添加会话数据,并通过 Session 属性使之可用于应用程序代码。 |
|
|
在请求结束和处理 ReleaseRequestState 或 EndRequest 事件时由会话状态模块调用,以清除当前 HttpContext 中的会话数据。 |
|
|
由会话状态模块调用,根据 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>
.NET Framework 安全性- AspNetHostingPermission 用于在宿主环境中使用 SessionStateUtility 类。要求值:LinkDemand。权限值:Minimal。

浙公网安备 33010602011771号