【发布时间】:2012-04-20 16:48:14
【问题描述】:
我一直在查看这段代码来创建一个基本的购物车,但缺点是它使用静态方法,因此购物车项目(当添加到购物车时)是跨会话共享的。有人可以指出如何修改 ShoppingCart 方法以消除此限制吗?
但我确定这是有问题的代码
// 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["ASPNETShoppingCart"] == null) {
Instance = new ShoppingCart();
Instance.Items = new List<CartItem>();
HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
} else {
Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
}
}
// A protected constructor ensures that an object can't be created from outside
protected ShoppingCart() { }
public void AddItem(int productId) {
// Create a new item to add to the cart
CartItem newItem = new CartItem(productId);
// If this item already exists in our list of items, increase the quantity
// Otherwise, add the new item to the list
if (Items.Contains(newItem)) {
foreach (CartItem item in Items) {
if (item.Equals(newItem)) {
item.Quantity++;
return;
}
}
} else {
newItem.Quantity = 1;
Items.Add(newItem);
}
}
【问题讨论】:
-
如果您使用包含用户特定数据的静态变量,所有用户都可以访问该数据。
-
@David - 购物篮内容使用 DES 加密,然后发布到第三方支付提供商并由第三方支付提供商处理,所以是的,我知道电子商务的安全/PCI 方面。至于购买第三方解决方案,对于这么小的项目来说,这确实不是一个选择。
-
@Matthew,谢谢,我也知道这一点 :O)