2

我不确定它是否会删除 cookie 上的所有内容,或者只是不从用户那里获取现有的 cookie,然后将其添加并返回。

这是代码:

[Authorize]
public ActionResult AddToCart(int productId, int quantity)
{
    //If the cart cookie doesn't exist, create it.
    if (Request.Cookies["cart"] == null)
    {
        Response.Cookies.Add(new HttpCookie("cart"));
    }

    //If the cart already has this item, add the amount to it.
    if (Request.Cookies["cart"].Values[productId.ToString()] != null)
    {
        int tmpAmount = Convert.ToInt32(Request.Cookies["cart"].Values[productId.ToString()]);
        Response.Cookies["cart"].Values.Add(productId.ToString(), (quantity + tmpAmount).ToString());
    }
    else
    {
        Response.Cookies["cart"].Values.Add(productId.ToString(), quantity.ToString());
    }

    return RedirectToAction("Index");
}

我使用了断点并且可以确认如果我在 cookie 中有一个项目,然后添加另一个不同的项目,代码运行正确不会执行Response.Cookies.Add(new HttpCookie("cart"));。所以我不认为我正在创建一个新的cookie。

事实上,我尝试添加相同的项目,我正确地看到该项目的金额增加了,而不是列出了两次。

我认为我的问题在于写入现有的 cookie?

添加另一个项目后的预期结果:

查看购物篮页面中的两项。

实际结果:

仅查看我在购物篮页面中添加的最新项目。

有什么明显的错误吗?这是我第一次涉足饼干。

4

2 回答 2

2

尝试每次创建一个新 cookie并添加所有应该存在的值(将现有值读入新 cookie,然后添加任何新值)。

从 MSDN 文档, http: //msdn.microsoft.com/en-us/library/ms178194.aspx

您不能直接修改 cookie。相反,更改 cookie 包括创建具有新值的新 cookie,然后将 cookie 发送到浏览器以覆盖客户端上的旧版本。

您还希望 cookie 保留在用户的硬盘上吗?如果是这样,您必须在 cookie 上设置过期日期。

于 2012-04-06T04:58:06.140 回答
0

我设法通过使用以下代码解决了这个问题:

似乎向键添加单个值会导致其余值消失。我所做的是创建一个辅助方法来接收现有的 cookie,以及即将添加的 productId 和数量。

下面是我如何调用它。

[Authorize]
public ActionResult AddToCart(int productId, int quantity)
{
    //If the cart cookie doesn't exist, create it.
    if (Request.Cookies["cart"] == null)
    {
        Response.Cookies.Add(new HttpCookie("cart"));
    }

    //Helper method here.
    var values = GenerateNameValueCollection(Request.Cookies["cart"], productId, quantity);
    Response.Cookies["cart"].Values.Add(values);

    return RedirectToAction("Index");
}

这是辅助方法:

private NameValueCollection GenerateNameValueCollection(HttpCookie cookie, int productId, int quantity)
{
    var collection = new NameValueCollection();
    foreach (var value in cookie.Values)
    {
        //If the current element isn't the first empty element.
        if (value != null)
        {
            collection.Add(value.ToString(), cookie.Values[value.ToString()]);
        }
    }

    //Does this product exist in the cookie?
    if (cookie.Values[productId.ToString()] != null)
    {
        collection.Remove(productId.ToString());
        //Get current count of item in cart.
        int tmpAmount = Convert.ToInt32(cookie.Values[productId.ToString()]);
        int total = tmpAmount + quantity;
        collection.Add(productId.ToString(), total.ToString());
    }
    else //It doesn't exist, so add it.
    {
        collection.Add(productId.ToString(), quantity.ToString());
    }

    if (!collection.HasKeys())
        collection.Add(productId.ToString(), quantity.ToString());

    return collection;
}
于 2012-04-06T15:14:11.173 回答