如何从.Net删除cookie

时间:2012-08-24 20:54:30

标签: c# .net cookies

  

可能重复:
  Delete cookie on clicking sign out

我想在用户退出时删除Cookie。

这是我的代码:

 if (HttpContext.Current.Request.Cookies["currentUser"] != null)
 {
     DeleteCookie(HttpContext.Current.Request.Cookies["currentUser"]);
 }


       public void DeleteCookie(HttpCookie httpCookie)
        {
            try
            {
                httpCookie.Value = null;
                httpCookie.Expires = DateTime.Now.AddMinutes(-20);
                HttpContext.Current.Request.Cookies.Add(httpCookie);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

但它不起作用。你有什么建议吗?

4 个答案:

答案 0 :(得分:60)

 HttpCookie currentUserCookie = HttpContext.Current.Request.Cookies["currentUser"];
 HttpContext.Current.Response.Cookies.Remove("currentUser");
 currentUserCookie.Expires = DateTime.Now.AddDays(-10);
 currentUserCookie.Value = null;
 HttpContext.Current.Response.SetCookie(currentUserCookie);

有效。

答案 1 :(得分:16)

您应该将Response's Cookie Expires更改为过去的值,而不是添加Cookie:

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

旁注:代替throw ex,您应该只throw来保持其堆栈跟踪。 C#: Throwing Custom Exception Best Practices

答案 2 :(得分:0)

将cookie(过去到期时间)添加到HttpContext.Current.Response.Cookies集合中。请求是读取服务器发送的cookie - 响应是将cookie发送回客户端。

答案 3 :(得分:0)

也许您可以使用Response.Cookies.Clear()或Response.Cookies.Remove()。