Skip to content
June 3, 2009 / kiranpatils

How to delete Cookie?

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: