简体   繁体   中英

Can't delete cookie in ASP.NET C#

I've got a logout.aspx that is called when the user clicks logout and there is where I want to delete the cookies but it just won't do it...

public partial class LogoutUser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie;

        cookie = Request.Cookies.Get("Basket");
        if (cookie == null)
        {
            cookie = new HttpCookie("Basket");
        }

        foreach (string item in cookie.Values.AllKeys)
        {
            Response.Cookies[item].Expires = DateTime.Now.AddDays(-1);                
        }

        cookie.Expires = DateTime.Now.AddDays(-1d);
        Response.Cookies["Basket"].Expires = DateTime.Now.AddYears(-1);    
        Session.Abandon();   

        Response.Redirect("~/Default.aspx");
    }
}

The cookie stores the values in the basket but after logging out I can still access the basket I don't know what's wrong.

Here is some relevant documentation .

I believe your mistake is in this line:

if (cookie == null)

You're checking for null, rather than checking for not null. Thus,

HttpCookie cookie;

    cookie = Request.Cookies.Get("Basket");
    if (cookie != null)
    {
        cookie = new HttpCookie("Basket");
        cookie.Expires = DateTime.Now.AddDays(-1);
        Response.Cookies.Add(cookie);
    }

    Response.Redirect("~/Default.aspx");

should do the trick.

Hope this is helpful.

Could it be this?

Session identifiers for abandoned or expired sessions are recycled by default. That is, if a request is made that includes the session identifier for an expired or abandoned session, a new session is started using the same session identifier. You can disable this by setting regenerateExpiredSessionId attribute of the sessionState configuration element to true . For more information, see Session Identifiers.

http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.abandon.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM