【发布时间】:2011-08-16 00:49:42
【问题描述】:
我用这个例子来创建一个购物车: http://net.tutsplus.com/tutorials/other/build-a-shopping-cart-in-aspnet/
这是一个很好的例子,它将购物车存储在 Session["cart"] 状态,它应该可以正常工作。
但事实并非如此。事件如果关闭浏览器,或者尝试不同的浏览器,它仍然保持状态?!?!
这里是构造函数+添加到购物车方法:
public List<CartItem> Items { get; private set; }
// 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["MPBooksCart"] == null)
{
Instance = new ShoppingCart();
Instance.Items = new List<CartItem>();
HttpContext.Current.Session["MPBooksCart"] = Instance;
}
else
{
Instance = (ShoppingCart)HttpContext.Current.Session["MPBooksCart"];
}
}
// A protected constructor ensures that an object can't be created from outside
protected ShoppingCart() { }
public void AddItem(int book_id)
{
// Create a new item to add to the cart
CartItem newItem = new CartItem(book_id);
// If this item already exists in our list of items, increase the quantity
// Otherwise, add the new item to the list
if (this.Items.Contains(newItem))
{
foreach (CartItem i in Items)
{
if (i.Equals(newItem))
{
i.Quantity++;
return;
}
}
}
else
{
newItem.Quantity = 1;
Items.Add(newItem);
}
}
能否请您告知问题可能是什么?
关于会话状态,我已经阅读了大约 2 个小时,并且到处都说关闭 broser 时它应该是 volatile 的,但在这种情况下它不是。
问候, 亚历克斯
【问题讨论】:
标签: c# asp.net session-state shopping-cart