我在我的网站的购物车应用程序中遇到会话冲突错误

时间:2012-06-15 04:41:16

标签: asp.net web-services

我正在使用下面的代码来维护Cart.There会话中的错误,当我打开我的网站更多然后浏览器有会话冲突,当我从我的一个浏览器然后选择另一个浏览器所以先前创建的会话已更新 虽然每个浏览器都必须有新的会话 请有人帮我理解会话中错误的区域。

#region Singleton Implementation

    // Readonly properties can only be set in initialization or in a constructor
    public static readonly ShoppingCart Instance;
    // The static constructor is called as soon as the class is loaded into memory
    static ShoppingCart()
    {
        // If the cart is not in the session, create one and put it there
        // Otherwise, get it from the session     
        if (HttpContext.Current.Session["ShoppingCart"] == null)
        {
            Instance = new ShoppingCart();
            Instance.Items = new List<CartItem>();
            HttpContext.Current.Session.Add("ShoppingCart", Instance);
        }
        else
        {
            Instance = (ShoppingCart)HttpContext.Current.Session["ShoppingCart"];
        }
    }

    // A protected constructor ensures that an object can't be created from outside
    protected ShoppingCart() { }

    #endregion

2 个答案:

答案 0 :(得分:1)

静态构造函数将被称为only once。所以其他人永远不会执行。

您可以使用检查会话是否为null的属性来创建实例,而不是此实现,否则返回存储的实例。

public Instance
{
set{ ... }
get{ ... }
}

答案 1 :(得分:0)

我发现ShopingCart类构造函数存在问题 当我直接使用静态构造函数时,我变得全球化,这就是我的购物车数据与其他用户购物车共享的方式 但现在我正在使用对象的属性。就像这样,

* 主要内容是get属性的if语句中的返回类型*

 public static ShoppingCart Instance
    {
        get
        {
            if (HttpContext.Current.Session["ShoppingCart"] == null)
            {
                // we are creating a local variable and thus
                // not interfering with other users sessions
                ShoppingCart instance = new ShoppingCart();
                instance.Items = new List<CartItem>();
                HttpContext.Current.Session["ShoppingCart"] = instance;
                return instance;
            }
            else
            {
                // we are returning the shopping cart for the given user
                return (ShoppingCart)HttpContext.Current.Session["ShoppingCart"];
            }
        }
    }