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

Good, so I really think I'm doing it right, but cookies are not 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 occurs, it finds the cookie again and moves on, as if I had never logged out. Any thoughts?

+49
c # cookies asp.net-mvc-3
Feb 25 '11 at 20:44
source share
3 answers

You're close You will need to use the Response object to write to the browser:

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

Learn more about MSDN, How to remove a cookie .

+96
Feb 25 2018-11-21T00:
source share

Cookies are stored on the client, not on the server, so Session.Clear will not affect them. In addition, Request.Cookies is populated by IIS and transferred to your page with each request per page; adding / removing cookies from this collection does nothing.

Try a similar action with Response.Cookies. This should force your client to overwrite the old cookie with the new one, which will lead to its expiration.

+9
Feb 25 '11 at 20:50
source share

I did this and it worked to clear (not delete) the session cookie:

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

Based on Metro's answer, I created this extension method to make the code reusable on 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); } 
+4
Apr 30 '12 at 18:01
source share



All Articles