ASP.NET之Cookie(坑爹的Response.Cookies.Remove)

来源:互联网 发布:软件测试总结报告 编辑:程序博客网 时间:2024/05/16 16:04

http://blog.csdn.net/bdstjk

在web开发中Cookie是必不可少的

.NET自然也有一个强大的Cookie操作类,我们用起来也非常方便,不过在使用中我们会发现一个坑爹的事情Response.Cookies.Remove删除不了Cookie。

例子如下:

protected void Page_Load(object sender, EventArgs e){    if (!IsPostBack)    {        HttpCookie UserInfo = new HttpCookie("UserInfo");        UserInfo.Value = "bdstjk";        Response.Cookies.Add(UserInfo);    }}protected void btnRemoveCookie_Click(object sender, EventArgs e){    Response.Cookies.Remove("UserInfo");    Response.Write("<script type=\"text/javascript\">alert(\"删除Cookie成功!\");</script>");}protected void btnCheckCookie_Click(object sender, EventArgs e){    if (Request.Cookies["UserInfo"] != null)    {        Response.Write("Cookie存在,"+Request.Cookies["UserInfo"].Value);    }    else    {        Response.Write("Cookie不存在");    }}

页面代码:

<asp:Button ID="btnRemoveCookie" runat="server" Text="删除Cookie"             onclick="btnRemoveCookie_Click" /><asp:Button ID="btnCheckCookie" runat="server" Text="检查Cookie"             onclick="btnCheckCookie_Click" />


运行代码测试,你会发现,怎么点删除按钮,cookie都存在,如下图:

这是为什么呢?明明是执行了删除cookie的操作,为什么就是删不掉呢?

我们去看看.NET的HttpCookieCollection实现源码

public void Remove(string name){    if (this._response != null)    {        this._response.BeforeCookieCollectionChange();    }    this.RemoveCookie(name);    if (this._response != null)    {        this._response.OnCookieCollectionChange();    }} 

这个操作在HttpCookieCollection这个集合里面删除了cookie,当服务器将数据传输到客户端的时候,不会包含这个已经在服务端删除了的Cookie的任何信息,浏览器也就不会对它做任何改变(remove方法只是不让服务器向客户机发送那个被删除的cookie,与此cookie留不留在客户机里无关)。所以cookie删除不掉的情况就出现。

那么如果我们想删除cookie应该怎么做呢?

把删除cookie的代码改成如下语句:

if (Request.Cookies["UserInfo"] != null){    Response.Cookies["UserInfo"].Expires = DateTime.Now.AddDays(-1);}Response.Write("<script type=\"text/javascript\">alert(\"删除Cookie成功!\");</script>");

我们再运行程序,测试:

好了。Cookie已经删除。通过设置Cookie的过期时间为负,强制使Cookie过期。就能实现我们需要的效果了。

既然Response.Cookies.Remove没有办法实现我们需要的效果,为什么微软还有留着呢,因为CookieCollection实现ICollection接口,romove是必须实现的方法,尽管它没多大的实际价值。而集合的romove也应该是这样的实现方式,只不过微软在写MSDN的时候,描述得太不清楚了,给我们造成了不小的麻烦。


 

 

 

 

 

原创粉丝点击