Automatic session exchange between many users [ASP.NET]

I used my own SessionWrapper class to handle Session in my ASP.NET project. It seems good, but I recently discovered that he has a funny mistake. If many user login on my site, their session will be exchanged or mixed. User A will have a session of user B, and possibly user C has a session of user A. It may change after the user refreshes the page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;

namespace MyNamespace
{
    public class SessionWrapper
    {
        public static string USER_SESSION = "userSession";

       public static void SetUserSession(string email, Dictionary<int, DateTime> products)
        {
            UserSession userSession = new UserSession() { Email = email, Products = products };
            System.Web.HttpContext.Current.Session.Add(USER_SESSION, userSession);
        }

        public static UserSession GetUserSession()
        {
            if (System.Web.HttpContext.Current.Session[USER_SESSION] != null)
            {
                return System.Web.HttpContext.Current.Session[USER_SESSION] as UserSession;
            }
            return null;
        }

        public static void RemoveUserSession()
        {
            if (System.Web.HttpContext.Current.Session[USER_SESSION] != null)
            {
                System.Web.HttpContext.Current.Session.Remove(USER_SESSION);
            }
        }
    }

    public class UserSession
    {
        private string email;
        private Dictionary<int, DateTime> products = new Dictionary<int, DateTime>();

        public string Email
        {
            get;
            set;
        }

        public Dictionary<int, DateTime> Products
        {
            get;
            set;
        }
    }
}
+3
source share
5 answers

, - , Jonas H, , , .

HttpContext.Current.Session.SessionID, , .

+3

:

private static Object locker = new Object();

public static UserSession GetUserSession()
{
  lock( locker)
  {
    if (System.Web.HttpContext.Current.Session[USER_SESSION] != null)
    {
      return System.Web.HttpContext.Current.Session[USER_SESSION] as UserSession;
    }
    return null;
  }
}
0

"" . AppDomain, .

. w3wp.exe, , . , .

, .

0

You add all sessions with the same key: USER_SESSION. You need to provide a unique key for each user (possibly an email address).

0
source

The code provided should behave as desired. If the problem really exists, as described, it should be caused by code elsewhere in the application.

0
source

All Articles