我不确定它是否会删除 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?
添加另一个项目后的预期结果:
在购物篮页面中看到两项商品。
实际结果:
仅查看我在购物篮页面中添加的最新商品。
有什么明显的错误吗?这是我第一次尝试 cookie。
最佳答案
尝试每次创建一个新 cookie 并添加应该存在的所有值(将现有值读入新 cookie,然后添加任何新值)。
来自 MSDN 文档,http://msdn.microsoft.com/en-us/library/ms178194.aspx
You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.
您还希望 cookie 保留在用户的硬盘上吗?如果是这样,您必须在 cookie 上设置到期日期。
关于c# - 使用 cookie 添加到购物车功能会删除所有内容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10039182/