How to delete cookies on an ASP.NET website

后端 未结 11 1922
傲寒
傲寒 2020-11-30 05:07

In my website when the user clicks on the \"Logout\" button, the Logout.aspx page loads with code Session.Clear().

In ASP.NET/C#, does this clear all co

相关标签:
11条回答
  • 2020-11-30 05:58

    Try something like that:

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

    But it also makes sense to use

    Session.Abandon();
    

    besides in many scenarios.

    0 讨论(0)
  • 2020-11-30 05:59

    No, Cookies can be cleaned only by setting the Expiry date for each of them.

    if (Request.Cookies["UserSettings"] != null)
    {
        HttpCookie myCookie = new HttpCookie("UserSettings");
        myCookie.Expires = DateTime.Now.AddDays(-1d);
        Response.Cookies.Add(myCookie);
    }
    

    At the moment of Session.Clear():

    • All the key-value pairs from Session collection are removed. Session_End event is not happen.

    If you use this method during logout, you should also use the Session.Abandon method to Session_End event:

    • Cookie with Session ID (if your application uses cookies for session id store, which is by default) is deleted
    0 讨论(0)
  • 2020-11-30 06:01

    Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(-1)

    0 讨论(0)
  • 2020-11-30 06:04

    Unfortunately, for me, setting "Expires" did not always work. The cookie was unaffected.

    This code did work for me:

    HttpContext.Current.Session.Abandon();
    HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
    

    where "ASP.NET_SessionId" is the name of the cookie. This does not really delete the cookie, but overrides it with a blank cookie, which was close enough for me.

    0 讨论(0)
  • 2020-11-30 06:08

    Though this is an old thread, i thought if someone is still searching for solution in the future.

    HttpCookie mycookie = new HttpCookie("aa");
    mycookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(mycookie1);
    

    Thats what did the trick for me.

    0 讨论(0)
提交回复
热议问题