开发者

Aspx, global instance of class, possible bug in code structure

开发者 https://www.devze.com 2023-03-14 12:33 出处:网络
I am tracking down a bug in some old aspx code. The problem is that one some very rare o开发者_运维问答ccations (1/10.000 pageviews or so) two users are mixed up, ie. user A sees user B data.

I am tracking down a bug in some old aspx code. The problem is that one some very rare o开发者_运维问答ccations (1/10.000 pageviews or so) two users are mixed up, ie. user A sees user B data.

Here is how the code is structured: We have a user class which is defined in a module like this:

Public Module MyGlobals
    Public myUser As CMyUser
End Module

On the loginpage, we validate the username/password and if valid then the coorosponding userid is loaded from db, and we do:

FormsAuthentication.SetAuthCookie(userid, False)

Then we redirect to the secure area. In the secure areas MasterPage, on event Page_Init, we then have:

If Context.User.Identity.IsAuthenticated then
    ' Initialize the user class (user data is loaded)
    MyGlobals.myUser = New CMyUser(Context.User.Identity.Name)
Else
    ' Redirect to loginpage
End If

Hereafter, is it safe to access the

MyGlobals.myUser

instance from every page which has the secure masterpage as masterpage, or could there be issues with this structure?


A VB.Net Module is like a static class with a private constructor and only static fields in C#.

That means, all variables declared in a module are shared across all threads. Hence every request(User) that's using this module will overwrite the old value.

I would strongly recommend to use Session to store user-sensitive data. But i'm not sure why you want to store the Username because it's already stored when using FormsAuthentication(as you've shown yourself above).

If you really need this wrapper, you could easily achieve it even in a static context via HttpContext.Current.Session:

Module MyGlobals
    Public Property myUser As CMyUser
        Get
            If HttpContext.Current.Session("CurrentUser") Is Nothing Then
                Return Nothing
            Else
                Return DirectCast(HttpContext.Current.Session("CurrentUser"), CMyUser)
            End If
        End Get
        Set(ByVal value As CMyUser)
            HttpContext.Current.Session("CurrentUser") = value
        End Set
    End Property
End Module
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号