如何在 C# 中将通用列表保存到 HttpCookie 中?

0 c# generics cookies asp.net-mvc shopping-cart

我用会话在 mvc5 中编写了一个购物车,但我想用 cookie 替换实现。这是订单操作:

public ActionResult OrderNow(int id)
    {
        if(Session["cart"]==null)
        {
            List<Item> cart = new List<Item>();
            cart.Add(new Item(de.Products.Find(id),1));
            Session["cart"] = cart;
        }
        else
        {
            List<Item> cart = (List<Item>)Session["cart"];
            int index = isExisting(id);
            if (index == -1)
                cart.Add(new Item(de.Products.Find(id), 1));
            else
                cart[index].Quantity++;
            Session["cart"] = cart;
        }
        return View("Cart");
    }
Run Code Online (Sandbox Code Playgroud)

和 Item 类是:

 public class Item
 {
    private Product pr = new Product();

    public Product Pr
    {
        get { return pr; }
        set { pr = value; }
    }


    private int quantity;

    public int Quantity
    {
        get { return quantity; }
        set { quantity = value; }
    }
    public Item(Product product, int quantity)
    {
        this.pr = product;
        this.quantity = quantity;
    }
} 
Run Code Online (Sandbox Code Playgroud)

我将 if 块替换为:

if(Request.Cookies["cart"]==null)
        {
            List<Item> cart = new List<Item>();
            cart.Add(new Item(de.Products.Find(id),1));
            Request.Cookies["cart"] = cart;
        }
Run Code Online (Sandbox Code Playgroud)

但我遇到了两个错误:无法将类型 'System.Collections.Generic.List' 隐式转换为 'System.Web.HttpCookie'
和属性或索引器 'System.Web.HttpCookieCollection.this[string]' 无法分配给 - 它是只读的。

我能怎么做?谢谢

Vol*_*hat 5

首先,您不能将对象保存到 cookie,您必须将其序列化,因为 cookie 接受字符串。最简单的方法是安装 Json.Net

Response.Cookies.Add(new HttpCookie("cart", JsonConvert.SerializeObject(cart)));
Run Code Online (Sandbox Code Playgroud)

然后你可以使用购物车

var cart = JsonConvert.DeserializeObject<List<Item>>(Request.Cookies["cart"])
Run Code Online (Sandbox Code Playgroud)

但是cookie的问题在于它们是有限的

我的建议是将Guid.NewGuid()购物车 ID存储在 cookie 中,然后使用该 ID 将您的购物车存储在数据库中。