【问题标题】:How to delete cookie from .Net [duplicate]如何从.Net中删除cookie [重复]
【发布时间】:2012-08-20 10:30:14
【问题描述】:

可能重复:
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);
            }
        }

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

【问题讨论】:

  • 我认为你不应该清除Value。 AFAIK,这就是识别 cookie 的方式。
  • 请注意,删除 cookie 只是二次清理。重要的部分是使服务器端 cookie 的值无效。

标签: c# .net cookies


【解决方案1】:

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

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

旁注:您应该只使用throw 而不是throw ex 来保留它的堆栈跟踪。 C#: Throwing Custom Exception Best Practices

【讨论】:

  • 如果什么都不做,为什么还要捕获异常?
  • 我试过了,但它不起作用。注销后我仍然可以看到用户名。 httpCookie.Expires = DateTime.Now.AddDays(-1);
  • @Dykam:您可以稍后决定记录它或做任何您想做的事情。我经常在第一个版本中添加TODO: implement logging。通过这种方式,您至少添加了 try/catch 以记住这可能会导致异常。
  • 如果我想删除一个cookie,然后创建另一个同名的cookie怎么办? Expires 会作用于我新创建的 cookie 吗?
【解决方案2】:
 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);

有效。

【讨论】:

  • 我知道这是一个旧答案,但对于新手来说,我认为先删除 cookie 并没有什么用处,因为它稍后会再次设置。
  • 我可以确认@JamesWilkins 所说的话。 Remove 不需要,因为 cookie 已被覆盖。
  • 根据docs.microsoft.com/en-us/dotnet/api/…,您应该使用 HttpContext.Current.Response.Set 而不是 HttpContext.Current.Response.SetCookie 不确定区别。
  • 我发现我需要删除行 - 否则我有很多同名过期的 cookie 徘徊,当读取值时,其中一个旧的“过期" 正在读取化身
【解决方案3】:

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

【讨论】:

【解决方案4】:

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

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 1970-01-01
    • 2012-11-29
    • 2010-10-29
    • 2018-03-09
    • 2019-08-13
    • 1970-01-01
    相关资源
    最近更新 更多