多个用户在购物车中看到相同的商品

Multiple user seeing the same items in shopping cart

我使用会话创建了一个购物车来存储要添加到 cart.Upon 部署的项目我发现购物车不是用户独有的,因为其他用户正在将项目添加到购物车由其他用户。

我试图在会话名称中使用登录用户名来使会话对该用户唯一,但它不起作用。

 public class ListOfDataset
 {

        static ListOfDataset()
        {

            string username = ClaimsPrincipal.Current.Identity.Name;

            // If the cart is not in the session, create one and put it there
            // Otherwise, get it from the session
            if (HttpContext.Current.Session[string.Format("ASPNETShoppingCart-{0}", username)] == null)
            {
                Instance = new ListOfDataset();
                Instance.Items = new List<DataSet>();
                HttpContext.Current.Session[string.Format("ASPNETShoppingCart-{0}", username)] = Instance;
            }
            else
            {
                Instance = (ListOfDataset)HttpContext.Current.Session[string.Format("ASPNETShoppingCart-{0}", username)];
            }
        }
}

已更新代码,else 语句中的错误 - 对象引用未设置且函数 ChekIfdatasetexist 始终存在 return 错误:

 public class ListOfDataset
    {



        public static ListOfDataset Instance
        {
            get
            {

                ListOfDataset cart = null;

                if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
                {
                    cart = new ListOfDataset();

                    cart.Items = new List<DataSet>();

                    HttpContext.Current.Session["ASPNETShoppingCart"] = cart.Items;

                }
                else
                {

                    cart.Items =(List<DataSet> )HttpContext.Current.Session["ASPNETShoppingCart"];
                }

                return cart;
            }
        }

        public List<DataSet> Items { get; private set; }

        public void AddItem(DataSet itemdataset)
        {

            Items.Add(itemdataset);

            HttpContext.Current.Session["ASPNETShoppingCart"] = Items;
        }

        public bool CheckIfDataSetExist(string servicename)
        {
            DataSet DataSetexist = null;

            if (Items != null)
            {
                DataSetexist = Items.Where(i => i.DataSetName == servicename).FirstOrDefault();
            }


            if (DataSetexist != null) return true;

            return false;
        }
    }

这里有两个问题。

  1. 正如有人在评论中所说,您已将实例成员设为静态,这意味着它将在应用程序范围内保持相同并在用户之间共享。
  2. 会话不是存储每个用户数据的最佳位置,因为它会耗尽您的服务器内存并且无法扩展。最好使用数据库来存储数据。