A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

How to delete Cookie?

Posted by kiranpatils on June 3, 2009

Challenge:

Today, i was implementing Remember Me Functionality in one of my application. I know you know what is “Remember Me” functionality. But when user says “Signout” i need to Forgot the user and to do that i need to delete my Cookie which i persisted when user says “Remember Me”..So, you will say simple delete cookie..But sorry sir you can’t delete cookie because it is on client side and user/browser can delete it..So, shall we ask user to delete cookie?? no we should not..then we just have one friend left “Browser”. But we need to cheat our friend[I strongly discourage cheating a real friend in real life :) ]. We don’t have any method by which we can delete the cookie directly but we can delete it..Want to know how??

Solution:

Okay, Boss relax!!! Here is the solution you should set the cookies Expiry date to past date..So, whenever Browser will see that it is expired it will discard that cookie.. I have created one method which you can directly use using Control Inheritance[COPY-PASTE] :) .. in which you just need to pass Cookie’s name rest smart method will manage :)

Here it is:

public static void RemoveCookie(string key)
{
//get cookie
HttpCookie cookie = null;
if (HttpContext.Current.Request.Cookies[key] != null)
{
cookie = HttpContext.Current.Request.Cookies[key];
//You can't directly delte cookie you should
//set its expiry date to earlier date cookie.Expires = DateTime.Now.AddDays(-1);
//Add expired cookie back to response - send to browser
HttpContext.Current.Response.Cookies.Add(cookie);
}
}

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>