尝试
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
答案 0 :(得分:4)
你有一个以编程方式删除cookie的正确概念:
HttpCookie myCookie = new HttpCookie("IsGuest");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);
然而,你错过了一点。的 The above change wonn'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");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);
}
// 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已经存在,则该方法不会从客户端中删除cookie。
答案 1 :(得分:0)
最好从列表中删除Cookie