Asp.Net - 如何使 Cookie 过期
Posted
技术标签:
【中文标题】Asp.Net - 如何使 Cookie 过期【英文标题】:Asp.Net - How to expire Cookie 【发布时间】:2014-10-07 18:48:59 【问题描述】:试过了
if (Request.Cookies["IsGuest"] != null)
Response.Cookies["IsGuest"].Expires = DateTime.Now.AddDays(-1);
//HttpCookie myCookie = new HttpCookie("IsGuest");
//myCookie.Expires = DateTime.Now.AddDays(-1d);
//Response.Cookies.Add(myCookie);
string a = Request.Cookies["IsGuest"].Value;
还尝试通过注释未注释的代码和取消注释已注释的代码来尝试,但是
string a = Request.Cookies["IsGuest"].Value;
一直在运行,Request.Cookies["IsGuest"]
永远不是null
【问题讨论】:
***.com/questions/6635349/…***.com/questions/3737285/… 那不是我的情况,评论者。 【参考方案1】:您了解了以编程方式删除 cookie 的正确概念:
HttpCookie myCookie = new HttpCookie("IsGuest");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);
但是,您错过了一分。 The above change won't be effective until the postback completes and subsequently user initiates a new request
。
MSDN 说:
The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.
所以,下面的代码在这里说明了更多::
protected void DeleteCookie_ButtonClick(object sender, EventArgs e)
if (Request.Cookies["IsGuest"] != null)
HttpCookie myCookie = new HttpCookie("IsGuest");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
// this will always be true here as the Request i.e HttpRequest isn't
// modified actually as the postback isn't complete and we are accessing
// the Cookies collection of same request (not a new request)
if (Request.Cookies["IsGuest"] != null)
Label1.Text = "Cookie Collection can't be modified without
making a new request";
// suppose after postback completes,
// user clicks a buttonn to check the cookie,
// which in turn is a new request/postback/....
protected void CheckCookie_ButtonClick(object sender, EventArgs e)
if (Request.Cookies["IsGuest"] != null)
Label1.Text = "Cookie is present!";
else
Label1.Text = "No Cookie is present!";
最后一点:
调用 Cookies 集合的Remove
方法会移除服务器端的 cookie,因此不会将 cookie 发送到客户端。但是,如果 cookie 已经存在,该方法不会从客户端删除它。
【讨论】:
很好的解释 :) 感谢您的出色回答 :) 我们可以从 web config 中设置 cookie 过期时间吗? @AuserP :网站范围的 cookie 设置通过 Web.config 元素最好从列表中删除 cookie
【讨论】:
怎么做?没有什么像 cookie.Remove() Response.Cookies.Clear()以上是关于Asp.Net - 如何使 Cookie 过期的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 asp.net 在 Chrome 中删除或过期 cookie
ASP.NET Core MVC:设置身份 cookie 过期
更改默认 ASP.NET 身份 两因素记住 Cookie 过期时间
如何使 ASP.NET Core 中的身份验证 cookie 无效?