【问题标题】:c# shopping cart [closed]c#购物车[关闭]
【发布时间】:2012-04-20 16:48:14
【问题描述】:

我一直在查看这段代码来创建一个基本的购物车,但缺点是它使用静态方法,因此购物车项目(当添加到购物车时)是跨会话共享的。有人可以指出如何修改 ShoppingCart 方法以消除此限制吗?

Full Code reference is here

但我确定这是有问题的代码

// 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)

标签: c# cart shopping


【解决方案1】:

我使用过几个商业购物车,每个购物车都将购物车存储在数据库中,甚至在结帐之前,并且只在 session.id 中存储了一个会话 ID。该 SessionID 被绑定为临时购物车中的字段。

我强烈建议遵循相同的模式。假设您的网站非常受欢迎。在内存中存储过多数据(无论是在会话中还是在应用程序中)都会遇到问题。

【讨论】:

    【解决方案2】:

    如果您使用的是静态变量,那么任何线程(无论是哪个用户)都可以访问该数据。这意味着您基本上在所有用户之间共享一张购物卡,我怀疑您不想要。

    相反,您可以有一个受保护的构造函数来防止手动实例化,然后有一个静态方法来读取 Session 对象并获取当前实例。至于你的静态方法填写你的Items 列表,你应该在构造函数中这样做。

    public static ShoppingCart GetInstance()
    {
        ShoppingCart cart = (ShoppingCart)Session["ASPNETShoppingCart"];
    
        if (cart == null)
        {
            Session["ASPNETShoppingCart"] = cart = new ShoppingCart();
        }
    
        return cart;
    }
    
    protected ShoppingCart()
    {
        Items = new List<CartItem>();
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-26
      • 2010-12-22
      • 2012-07-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 2011-01-29
      • 2011-06-14
      • 1970-01-01
      相关资源
      最近更新 更多