c# - 使用 cookie 添加到购物车功能会删除所有内容吗?

标签 c# asp.net-mvc-3 cookies cart

我不确定它是否会删除 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/

相关文章:

c# - 在 C# 中扩展 DataTable

c# - 表达式的增量值

javascript - 使用 JQuery 将行中包含的属性链接添加到表中

asp.net-mvc-3 - ASP.NET MVC 中全局错误/异常处理的最佳实践是什么?

java - 有没有办法在java小程序中获取HttpOnly cookies数据?

c# - 在android中实现滑动和点击相对布局的最佳方法是什么?

asp.net - 带条件的 Linq 计数

c# - 生成进程时如何重定向标准输出

php - 如何解决 Apache 2.4 和 PHP 7.1 上 Chrome 中的跨站点 Google Analytics cookie `SameSite=None` 警告?

java - 特殊字符被 tomcat cookie 解析器拒绝