c.dunlap
c.dunlap

Reputation: 600

ASP.NET Remove Session/Cookies

I've looked around and found how to delete cookies on the client browser either using an expiration for the cookies or deleting them on browser exit by not providing an expiration.

I need to set the cookies in my web app to delete after a specific amount of time, but also if the browser exits or crashes. Is this possible?

Thanks in advance!

Upvotes: 3

Views: 2991

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

Is this possible?

No, this is not possible out of the box. There are 2 types of cookies:

  1. persistent: one with expires property set for a given date => those cookies are stored as files on the client browser and survive browser restart. The will be sent along each request the client performs until the date at which they are meant to expire is reached or until the server explicitly removes them.
  2. session cookies: one without expires property being set. Those live only in the memory of the current browser process but will never expire (until the browser is closed or until the server explicitly removes them).

So for your scenario you could use session cookies by including the created at date in the value. Then on the server upon each request you could read this value and compare with the current date. If the desired period has elapsed simply expire the cookie so that it is no longer sent on subsequent requests. By the way this technique is used the Forms Authentication module in ASP.NET. You specify a timeout in your web.config and decide whether you want to use a sliding expiration or not and then on each request the server checks whether the timeout is reached in order to take the decision of invalidating the cookie or renewing it (if sliding expiration is enabled).

Upvotes: 4

Related Questions