55

Ok, so I really think I am doing this right, but the cookies aren't being cleared.

 Session.Clear();
 HttpCookie c = Request.Cookies["MyCookie"];
 if (c != null)
 {
     c = new HttpCookie("MyCookie");
     c["AT"] = null;
     c.Expires = DateTime.Now.AddDays(-1);
     Request.Cookies.Add(c);
 }

 return RedirectToAction("Index", "Home");

When the redirect happens, it finds the cookie again and moves on as though I never logged out. Any thoughts?

3 Answers 3

107

You're close. You'll need to use the Response object to write back to the browser:

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

More information on MSDN, How to: Delete a Cookie.

4
  • 9
    Bah! Can't believe I got Response and Request mixed up. Thanks for your help! David
    – David
    Feb 25, 2011 at 21:14
  • anything new in 2017 ?
    – Vikas Rana
    Jul 22, 2017 at 6:12
  • 3
    @VikasRana Self driving cars are a big deal nowadays.
    – Uwe Keim
    Sep 25, 2017 at 12:28
  • 1
    @UweKeim Thanks a lot, I didn't know about this :p
    – Vikas Rana
    Sep 26, 2017 at 5:21
9

Cookies are stored on the client, not on the server, so Session.Clear won't affect them. Also, Request.Cookies is populated by IIS and given to your page with each request for a page; adding/removing a cookie from that collection does nothing.

Try performing a similar action against Response.Cookies. That should cause your client to overwrite the old cookie with the new one, causing it to be expired.

5

I did this and it worked for clearing (not deleting) a session cookie:

HttpContext.Response.Cookies.Set(new HttpCookie("cookie_name"){Value = string.Empty});

Based on Metro's response I created this extension method to make the code reusable in any controller.

/// <summary>
/// Deletes a cookie with specified name
/// </summary>
/// <param name="controller">extends the controller</param>
/// <param name="cookieName">cookie name</param>
public static void DeleteCookie(this Controller controller, string cookieName)
{
    if (controller.HttpContext.Request.Cookies[cookieName] == null)
            return; //cookie doesn't exist

    var c = new HttpCookie(cookieName)
                {
                    Expires = DateTime.Now.AddDays(-1)
                };
    controller.HttpContext.Response.Cookies.Add(c);
}
1
  • tried several things with only having AuthorizationContext and your solution finally worked Dec 22, 2014 at 1:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.