我不确定它是否删除了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。
答案 0 :(得分:2)
每次尝试创建新Cookie 并添加应该存在的所有值(将现有值读入新Cookie然后添加任何新值)。< / p>
从MSDN文档中http://msdn.microsoft.com/en-us/library/ms178194.aspx
您无法直接修改Cookie。相反,更改cookie 包括用新值创建一个新的cookie,然后发送 cookie到浏览器覆盖客户端上的旧版本。
您是否也希望cookie能够持久保存到用户的硬盘中?如果是这样,您必须在cookie上设置到期日期。
答案 1 :(得分: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;
}