Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Session Class and Multiple Users

I am building a class to store User ID and User Role in a session. I'm not sure how this class will behave when multiple users are on the site at the same time. Does anyone see a problem with this?

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; }
        }

}
like image 561
Tony Borf Avatar asked Sep 18 '09 19:09

Tony Borf


2 Answers

The code you posted is the exact replica of some code we have here.

It has been working fine for 2 years now.

Each users access is own session. Every request made to the server is a new thread. Even though 2 request are simultaneous, the HttpContext.Current is different for each of those request.

like image 57
Jean-Francois Avatar answered Oct 07 '22 22:10

Jean-Francois


You'll get a new session for each connection. No two users will ever share session. Each connection will have its own SessionID value. As long as the user stays on your page (doesn't close the browser, etc.) the user will retain that session from one request to the next.

like image 24
Jarrett Meyer Avatar answered Oct 07 '22 22:10

Jarrett Meyer