2012-02-17 71 views
0

我是很新的vb.net因爲我更是一個PHP開發人員,但無論如何的。我已經構建了一個Web應用程序,但我的用戶似乎正在共享我不想要的同一個會話,並且無法理解原因。我從一個模塊的全局屬性中訪問存儲所有會話信息的對象,這可能是原因嗎?VB.NET Web應用程序 - 不需要用戶會話共享

的代碼如下:你爲什麼要使用一個靜態類(模塊)作爲信息庫用於Session對象

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

爲什麼使用靜態類(Module)作爲Session對象的存儲庫?靜態意味着應用廣泛。 'mUserSession'也是隱式靜態的,因此所有的用戶共享同一個Session。 – 2012-02-17 12:01:01

+0

啊...就像我剛纔說的,vb.net新手。我只想要一個全局(非靜態)的方式來訪問我的會話對象,而不是重複同樣的檢查和訪問。我的印象是一個模塊只是全局可訪問的功能存儲空間,而不是靜態的。 – James 2012-02-17 12:05:39

回答

2

?靜態意味着應用廣泛。 mUserSession也是隱式靜態的,因此所有用戶共享同一個Session。其實線

mUserSession = value 
中的getter/setter

mUserSession = HttpContext.Current.Session("user") 

被覆蓋它的所有用戶。

你可以換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而您正在返回單個/共享實例。

+0

是的,我認爲這一點,因爲它類似於我將在PHP中完成它。如果我知道一個模塊的靜態影響,我會有。我可以問另外兩個問題(如果您計算這個問題,可以選擇三個問題),您爲什麼選擇通過CType使用DirectCast?我可以轉換gUserSession返回MySession.Current,所以我不必重寫我的所有代碼或將同樣的問題適用? – James 2012-02-17 12:41:59

+1

1)http://stackoverflow.com/a/3056582這也是值得推薦的瞭解所涉及的實際類型,即使只是出於學習目的;) 2),只要用我的'Current',其重命名爲'gUserSession'並將'MySession'重命名爲'UserSession'。 – 2012-02-17 12:49:10

+0

@James:最後一個注意事項:僅對[Extensions](http://msdn.microsoft.com/zh-cn/library/bb384936.aspx)使用模塊。在99.999%的其他情況下,您應該使用可能包含靜態成員的(非靜態)類。 – 2012-02-17 14:36:54

相關問題