开发者

ASP.NET Session Issue

开发者 https://www.devze.com 2022-12-20 02:56 出处:网络
I have a custom ASP.NET session manager class as follows: public sealed class SessionManager : Page { private const string USER = \"User\";

I have a custom ASP.NET session manager class as follows:

public sealed class SessionManager : Page
    {
        private const string USER = "User";

        private static readonly SessionManager _instance = new SessionManager();

        private SessionManager()
        {
        }


        public static SessionManager Instance
        {
            get { return _instance; }
        }


        public User User
        {
            get { return Session[USER] as User; }
            set { Session[USER] = value; }
        }

    }

After a user successfully logs int开发者_Go百科o the system his full name is displayed on the Home page. Below is the problem I am facing:

1) I first log into the system as John and John's full name is displayed on the homepage and the corresponding user object is kept in session.

2) Now from a different PC I login to the system as Mark. Now Mark's full name is displayed on the homepage and the corresponding user object is kept in session.

3) Now when I go to the PC from which John has logged in and refresh the homepage I see Marks name instead of Johns name.

What could be the reason for this strange behavior?


Your class inherits from System.Web.UI.Page, which sets its Session member to HttpContext.Current.Session on first access. Since you have a singleton, it will always refer to the first session in which the User property was accessed.

You probably should do something like this:

public sealed class SessionManager
{
    private const string USER = "User";

    private static readonly SessionManager _instance = new SessionManager();

    private SessionManager()
    {
    }

    public static SessionManager Instance
    {
        get { return _instance; }
    }

    public User User
    {
        get { return HttpContext.Current.Session[USER] as User; }
        set { HttpContext.Current.Session[USER] = value; }
    }
}
0

精彩评论

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