我对vb.net很陌生,因为我更像是一个PHP开发人员,但无论如何。我已经构建了一个Web应用程序,但我的用户似乎正在共享同一个我不想要的会话,并且无法理解为什么。我从模块中的全局属性访问我存储所有会话信息的对象,这可能是原因吗?
代码如下:
Module SiteWide
Private mUserSession As New MyLib.User.UserSession
Public Property gUserSession() As MyLib.User.UserSession
Get
If Not HttpContext.Current Is Nothing AndAlso Not HttpContext.Current.Session Is Nothing Then
If Not HttpContext.Current.Session("user") Is Nothing Then
mUserSession = HttpContext.Current.Session("user")
End If
End If
Return mUserSession
End Get
Set(ByVal value As MyLib.User.UserSession)
mUserSession = value
If Not HttpContext.Current Is Nothing AndAlso Not HttpContext.Current.Session Is Nothing Then
HttpContext.Current.Session("user") = value
End If
End Set
End Property
End Module
答案 0 :(得分:2)
为什么使用静态类(Module)作为Session对象的存储库?静态意味着应用广泛。 mUserSession
也是隐含的,因此所有用户共享同一个Session。实际上是行
mUserSession = value
和
mUserSession = HttpContext.Current.Session("user")
getter / setter中的会覆盖所有用户。
您可以将Session对象包装在您自己的类中,只是为了简化:
例如:
Public Class MySession
' private constructor
Private Sub New()
End Sub
' Gets the current session.
Public Shared ReadOnly Property Current() As MySession
Get
Dim session As MySession = DirectCast(HttpContext.Current.Session("__MySession__"), MySession)
If session Is Nothing Then
session = New MySession()
HttpContext.Current.Session("__MySession__") = session
End If
Return session
End Get
End Property
' **** add your session properties here, e.g like this:
Public Property MyID() As Guid
Get
Return m_ID
End Get
Set(value As Guid)
m_ID = value
End Set
End Property
Private m_ID As Guid
Public Property MyDate() As DateTime
Get
Return m_MyDate
End Get
Set(value As DateTime)
m_MyDate = Value
End Set
End Property
Private m_MyDate As DateTime
End Class
注意:Current
- 属性也是共享/静态的,但区别在于我返回HttpContext.Current.Session
而你正在返回单个/共享实例。