[英]classic asp.net shoppingcart session state
我用这个例子创建了一个购物车: http://net.tutsplus.com/tutorials/other/build-a-shopping-cart-in-aspnet/
这是一个很好的例子,它将购物车存储在 Session["cart"] state 中,它应该可以正常工作。
但事实并非如此。 事件如果关闭浏览器,或者尝试不同的浏览器,它仍然保持state???!
这是构造函数 + 添加到购物车方法:
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 个小时关于 session state 以及它说它在关闭 broser 时应该是易失性的,但在这种情况下它不是。
问候,亚历克斯
我不太确定使用 Singleton 模式来保存 session 的实例。 如果您考虑一下,session 对于每个用户和访问该网站的每个浏览器都必须是唯一的。 Singleton 模式创建一个全局唯一实例。 我不知道你做了多少 asp.net 但是,以防你对 asp.net 相当陌生,session 将是特定浏览器实例所独有的。 这意味着访问 Session["MPBooksCart"] 的每个浏览器都将访问他们自己唯一的数据副本。 默认情况下,asp.net session 将保存其数据 20 分钟(可以在数据库中配置)。 如果我正在编写购物车,我可能会直接使用数据库中的购物车表和 caritems 表。 店面网站的一个很好的例子是 Rob Connery 的MVC Samples App 。 这是一个 ASP.Net MVC 应用程序,因此如果您不熟悉 MVC,您可能会发现这有点难以理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.