Search code examples
c#cookiesasp.net-mvc-3

How do you clear cookies using asp.net mvc 3 and c#?


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?


Solution

  • 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.