静态会话类和多用户

问题描述 投票:0回答:3

我正在构建一个类来在会话中存储用户 ID 和用户角色。我不确定当多个用户同时访问该网站时,此类将如何表现。有人发现这个有问题吗?

public static class SessionHandler
    {   
        //*** Session String Values ***********************

        private static string _userID = "UserID";
        private static string _userRole = "UserRole";

        //*** Sets and Gets **********************************************************

        public static string UserID
        {
            get
            {
                if (HttpContext.Current.Session[SessionHandler._userID] == null)
                { return string.Empty; }
                else
                { return HttpContext.Current.Session[SessionHandler._userID].ToString(); }
            }
            set
            { HttpContext.Current.Session[SessionHandler._userID] = value; }

        }
        public static string UserRole
        {
            get
            {
                if (HttpContext.Current.Session[SessionHandler._userRole] == null)
                { return string.Empty; }
                else
                { return HttpContext.Current.Session[SessionHandler._userRole].ToString(); }
            }
            set
            { HttpContext.Current.Session[SessionHandler._userRole] = value; }
        }

}
c# asp.net session
3个回答
7
投票

您发布的代码与我们此处的某些代码完全相同。

现在已经正常工作2年了。

每个用户访问自己的会话。向服务器发出的每个请求都是一个新线程。尽管 2 个请求是同时发生的,但每个请求的 HttpContext.Current 都是不同的。


4
投票

每次连接您都会获得一个新会话。没有两个用户会共享会话。每个连接都有自己的

SessionID
值。只要用户停留在您的页面上(不关闭浏览器等),用户就会从一个请求到下一个请求保留该会话。


0
投票

这对于访问您的应用程序的多个用户来说效果很好,因为将为同时访问应用程序的所有不同用户生成不同的 sessionid。如果您在系统中定义了两个不同的会话变量,它将以类似的方式工作。 这就像使用静态包装类 SessionHandler 包装两个会话状态。

© www.soinside.com 2019 - 2024. All rights reserved.