从cookie中删除特定值

时间:2014-04-04 06:12:42

标签: c# asp.net

我有一个cookie“愿望清单”。它包含id的列表。我想从cookie中删除一个特定的id。我正在对cookie进行反序列化,但我无法从中删除特定的id。我正在处理的代码如下:

public int DeleteFromWishlist(long pid)
{
  List<Int64> ls_p = new List<Int64>();
  ls_p = Deserialize<List<Int64>>(Convert.ToString(HttpContext.Current.Request.Cookies["wishlist"].Value));
  var prd = ls_p;
  foreach (var item in prd)
   {
     if (item == pid)
     {
         string it = item.ToString();
         HttpContext.Current.Response.Cookies["wishlist"].Values.Remove(it);
     }
   }
}

现在上面的代码正在从wishlist cookie中删除所有值。

3 个答案:

答案 0 :(得分:1)

if (Request.Cookies["wishlist"] != null)
{
    Response.Cookies["wishlist"].Expires = DateTime.Now.AddDays(-1);   
}

要删除特定项目,请尝试以下代码(仅覆盖)

Response.Cookies["wishlist"].Values["YourItem"] = String.Empty;

答案 1 :(得分:0)

从列表中删除它,然后重置cookie

答案 2 :(得分:0)

我解决了它:

  public int DeleteFromWishlist(long pid)
    {
        int result = 0;
        List<Int64> ls_p = new List<Int64>();
        HttpCookie mycookie = null;
        ls_p = Deserialize<List<Int64>>(Convert.ToString(HttpContext.Current.Request.Cookies["wishlist"].Value));

        var prd = ls_p;

        {
            {
                ls_p.Remove(ls_p.FirstOrDefault(p=>p==pid));
                string data = SerializeItem<List<Int64>>(prd);
                mycookie = HttpContext.Current.Request.Cookies["wishlist"];
                mycookie.Value = data;
                mycookie.Expires = DateTime.Now.AddMonths(1);
                HttpContext.Current.Response.Cookies.Add(mycookie);
                result = 1;
            }

        }

        return result;

    }