如何在 c# 中为 asp.net 中的购物车详细信息附加 cookie

how to append a cookie for shopping cart details in asp.net in c#

我想在 cookie 名称购物车中附加新产品的产品 ID,所以任何人都可以帮助我吗

protected void lnkAddToCart_Click(object sender, EventArgs e)
{

    HttpCookie CartCookie=Request.Cookies["cart"];
    if (CartCookie != null)
    {
        string str = CartCookie.ToString();
        str= str + ";"+ _ProductID.ToString();
        Response.Cookies["cart"].Value = str;

    }
    else
    {
         CartCookie = new HttpCookie("cart");
       CartCookie["Cart"] = _ProductID.ToString();
       CartCookie.Expires = DateTime.Now.AddYears(1);
       Response.Cookies.Add(CartCookie);
    }
}

设置 Cookie

public void AddToCartCookie(List<string> listCookie)
{        
      string objCartListString = string.Join(",", listCookie);

      if (Request.Cookies["CartCookie"] == null)
          Response.Cookies["CartCookie"].Value = objCartListString;
      else
          Response.Cookies["CartCookie"].Value = Request.Cookies["CartCookie"].Value + "|" + objCartListString;

      Response.Cookies["CartCookie"].Expires = DateTime.Now.AddYears(30);
}

这里listCookie是字符串列表 string productName, quantity, price 等;

然后通过like拆分取回

if (Request.Cookies["CartCookie"] != null)
{
        string objCartListString = Request.Cookies["CartCookie"].Value.ToString();
        string[] objCartListStringSplit = objCartListString.Split('|'); 
        foreach(string s in objCartListStringSplit)
        {
            string[] ss = s.Split(',');
            productName = ss[0];
            quantity = Convert.ToDouble(ss[1]);
            price = Convert.ToDecimal(ss[3]);
           .........                    
        }
}