【发布时间】: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并没有改变我的输出