Remove Cookie in ASP.NET

I was working on the Cookies using the HTTPCookie class in ASP.NET. Though it is simple to add cookie and use them in the program but I really struggle to remove the cookies. I tried initially

  1. Get the reference to the cookie.
  2. Use the Response.Cookies.Remove method to remove the cookie.

I expected the API to behave as per the name i.e. delete the cookie but to my utter shock it didn’t work. After long search I found the solution. The key was to make the cookie expire instead of removing it from the collection

Response.Cookies[“MY_COOKIE”].Expires = DateTime.Now;

This works perfectly for me.

 

Advertisements

3 Responses

  1. Here’s a thought about using DateTime.Now, how is this affected by time-zones of the visitor’s cookie?

    If the web-server is in Sydney, Australia they would be UTC+10 … so if a visitor from Hawaii (UTC-10) need to wait 20 hours for the cookie to expire?

    Maybe try DateTime.UtcNow.AddDays(-1) for the cookie expiration?

  2. are you talking about persistent or non persistent cookie, how we remove non persistent cookie

  3. After setting the cookie Expiration to the previous date. Again create a new cookie. As we cannot completely destroy the cookie on the local user system.

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: