【问题标题】:Deleting specific key/values from cookie in C#从 C# 中的 cookie 中删除特定的键/值
【发布时间】:2018-02-19 16:35:18
【问题描述】:

我有一个购物车,它将所有购物车项目添加到一个 cookie 中,所以当用户去他的“购物车”结账时,项目会填充该页面......我有这部分工作,但我有一个 @ 987654322@ 请求当用户想要从购物车中删除一个项目时,该项目似乎没有从 cookie 中删除该项目。

我的 cookie 字符串如下所示(例如,如果他们已将两件商品添加到购物车:1=X Large&2=Small,其中左侧是 productId,右侧是 MerchSize

这是我的代码:

[HttpPost]
public ActionResult RemoveItem(int? ID)
{
    //pull existing cookie and get string value
    string cookie = "";
    if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("CartCookie"))
    {
        cookie = this.ControllerContext.HttpContext.Request.Cookies["CartCookie"].Value;
    }

    if (cookie != "")
    {
        //convert string cookie into a dictionary
        Dictionary<string, string> keyValuePairs = cookie.Split('&')
        .Select(value => value.Split('='))
        .ToDictionary(pair => pair[0], pair => pair[1]);

        //delete the existing cookie if it exists at all
        if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("CartCookie"))
        {
            HttpCookie deleteCookie = this.ControllerContext.HttpContext.Request.Cookies["CartCookie"];
            deleteCookie.Expires = DateTime.Now.AddDays(-1);
            this.ControllerContext.HttpContext.Response.Cookies.Add(deleteCookie);
            System.Diagnostics.Debug.WriteLine("cookie deleted");
        }

        // remove a specific key/value pair from the dictionary
        if (keyValuePairs.Remove(ID.Value.ToString()))
        {

            HttpCookie updatedCookie = Request.Cookies["CartCookie"];
            if (updatedCookie == null)
            {
                // no cookie found, create it
                updatedCookie = new HttpCookie("CartCookie");

                foreach (KeyValuePair<string, string> kvp in keyValuePairs)
                {
                    updatedCookie.Values[kvp.Key] = kvp.Value;
                }
            }
            else
            {
                // update the cookie values
                foreach (KeyValuePair<string, string> kvp in keyValuePairs)
                {
                    System.Diagnostics.Debug.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
                    updatedCookie.Values[kvp.Key] = kvp.Value;
                }
            }

            // update the expiration timestamp
            updatedCookie.Expires = DateTime.UtcNow.AddDays(30);

            // overwrite the cookie
            Response.Cookies.Add(updatedCookie);

            //print the value of the new cookie
            string newcookie = "";
            if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("CartCookie"))
            {
                newcookie = this.ControllerContext.HttpContext.Request.Cookies["CartCookie"].Value;
            }
            System.Diagnostics.Debug.WriteLine(newcookie);

        }
        else
        {
            // dictionary doesn't contain above key
        }  
}

    return Json(true);

}

如您所见,我在不同的行打印输出,这是我在控制台中看到的:

cookie deleted //confirms that the cookie delete function runs
Key = 1, Value = X Large //shows that only one item is in the NEW dictionary
1=X Large&2=Small //shows that the new cookie still has both items

【问题讨论】:

  • Cookie not updating 可能重复。
  • @RMH 有点像!但是,我了解您需要完全删除并重新添加新的 cookie。但是,在删除 cookie(或者我认为是)后,我仍然在最后的 cookie 中看到相同的信息
  • @mjwills 没有任何变化,这显然让我相信我的删除块不起作用。我似乎无法追踪为什么..
  • @mjwills 我相信是request,因为我需要从浏览器更改的更新cookie。但是,我尝试使用 response 并没有改变我的输出

标签: c# asp.net cookies


【解决方案1】:

看来我之前对可能重复的评论是不正确的。经过进一步检查,我注意到,当 cookie 已经存在时,值会更新,但是需要删除的值实际上并没有从 cookie 本身中删除。


所以问题出在以下代码中:

HttpCookie updatedCookie = Request.Cookies["CartCookie"];
if (updatedCookie == null)
{
    // [omitted]
}
else
{
    // update the cookie values
    foreach (KeyValuePair<string, string> kvp in keyValuePairs)
    {
        System.Diagnostics.Debug.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
        updatedCookie.Values[kvp.Key] = kvp.Value;
    }
}

当 cookie 已经存在时,它所采用的并且更新keyValuePairs 字典中的值。在前面的语句中,您已经从字典中删除了一个值,但是字典没有绑定到 cookie,这意味着您删除的键仍然存在于 cookie 中。

您需要确保 cookie 值为空:

// Clear the cookie value entirely
cookie.Value = null;

或者更好的是,删除一个特定的键:

// Remove a specific key from the cookie value
cookie.Values.Remove(ID.Value.ToString());

后者对我来说似乎更可取,因为它不需要您将值解析到字典中并更新它们。


作为旁注,如果您想更新 cookie 的值,则不需要删除它。只需将更新后的 cookie 及其新属性(值、时间等)发回,客户端上的现有 cookie 就会更新。

【讨论】:

  • 非常好,感谢您检查这个问题。你是对的,我在删除时错过了 cookie 上的 null 值。这修复了它:)
猜你喜欢
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 2011-12-09
  • 2015-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多