这当然不应该是这样的,我是说为什么仅为当前
HTTPContext
生成一个全新的会话如此困难?太奇怪了!无论如何,我编写了一个小巧的实用程序类来“只是这样做”:(抱歉代码格式/高亮/Visual Basic,我一定做错了些什么)
Imports System.Web
Imports System.Web.SessionState
Public Class SwitchSession
Public Shared Sub SetNewSession(ByVal context As HttpContext)
' This value will hold the ID managers action to creating a response cookie
Dim cookieAdded As Boolean
' We use the current session state as a template
Dim state As HttpSessionState = context.Session
' We use the default ID manager to generate a new session id
Dim idManager As New SessionIDManager()
' We also start with a new, fresh blank state item collection
Dim items As New SessionStateItemCollection()
' Static objects are extracted from the current session context
Dim staticObjects As HttpStaticObjectsCollection = _
SessionStateUtility.GetSessionStaticObjects(context)
' We construct the replacement session for the current, some parameters are new, others are taken from previous session
Dim replacement As New HttpSessionStateContainer( _
idManager.CreateSessionID(context), _
items, _
staticObjects, _
state.Timeout, _
True, _
state.CookieMode, _
state.Mode, _
state.IsReadOnly)
' Finally we strip the current session state from the current context
SessionStateUtility.RemoveHttpSessionStateFromContext(context)
' Then we replace the assign the active session state using the replacement we just constructed
SessionStateUtility.AddHttpSessionStateToContext(context, replacement)
' Make sure we clean out the responses of any other inteferring cookies
idManager.RemoveSessionID(context)
' Save our new cookie session identifier to the response
idManager.SaveSessionID(context, replacement.SessionID, False, cookieAdded)
End Sub
End Class
在请求的其余部分中它能够正常工作,并且正确地识别自己为新会话(例如,HTTPContext.Current.Session.SessionID
返回新生成的会话标识符)。
于是当下一个请求到达服务器时,HTTPContext.Session
(一个HTTPSessionState
对象)正确地使用相同的SessionID
进行标识,但将IsNewSession
设置为True
,并为空,失去了前一个请求中设置的所有会话值。
因此,在初始请求中删除前一个HTTPSessionState
对象时,必须有一些特殊的处理,例如事件处理程序、回调等,可以处理跨请求保留会话数据的问题,或者我可能错过了某些东西?
有人有任何神奇的方法可分享吗?
SwitchSession
类添加一些状态(replacement
会话)并为活动的ASP.NET应用程序实例连接SessionStateModule
事件来进化它。当Start
事件触发时,它会检查ASP.NET生成的会话是否具有相同的SessionID
,并将所有会话状态值从上一个请求复制到其中。显然,只有在所有请求都通过处理前一个请求的HTTPApplication
实例时才有效。我正在使用反射器深入挖掘SessionStateModule
,但这不是很好看。请投票支持这个问题! - Rabid