如何从.Net删除cookie

cag*_*gin 28 .net c# cookies

可能重复:
点击退出时删除cookie

我想在用户注销时删除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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

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

cag*_*gin 63

 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);
Run Code Online (Sandbox Code Playgroud)

有用.

  • 我知道这是一个古老的答案,但对于新手来说,我认为首先删除cookie不会有用,因为无论如何它都会在以后再次设置. (8认同)
  • 根据此https://learn.microsoft.com/en-us/dotnet/api/system.web.httpresponse.setcookie?view=netframework-4.8,您应该使用 HttpContext.Current.Response.Set 而不是 HttpContext.Current。 Response.SetCookie 不确定其中的区别。 (2认同)

Tim*_*ter 18

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

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

旁注:而不是throw ex你应该只是throw为了保持其堆栈跟踪.C#:抛出自定义异常最佳实践