Question

I am interested on how to make a regular HttpCookie object into a cookie that expires at the end of a session. I am not interested in someone showing me HttpContext.Session. How does a session cookie look in the response headers compared to a normal cookie? How can I modify a HttpCookie to expire at the end of a session? Thanks!

Was it helpful?

Solution

A session cookie is just a cookie that doesn't have any expiration date set.

Response.Cookies.Add(new HttpCookie("name", "value"));

or:

Response.Cookies["name"] = "value";

OTHER TIPS

A cookie with an expiration of DateTime.MinValue (1/1/0001) will expire at the end of the session. This is the default expiration date for a cookie in asp.net.

You can force a cookie to be deleted off the client imediately by setting the expiration date to something before "now" (DateTime.Now.AddDays(-1d)) in which case it will be deleted when it hits the client.

If we had nullable types back when HttpCookie was coded my guess is that a null date would equate to a session based cookie and anything else would translate into the expiration value but this is not the case.

Expiration of cookie:

  • Session cookie - Expires date should be DateTime.MinValue which is 1/1/0001 00:00:00
  • Normal cookie (Time limited) - Expires date is any future date equal or more than the current DateTime.Now.
  • Deleted cookie - anytime between DateTime.MinValue and DateTime.Now.

To change the cookie into session cookie, simply assign MinValue.

httpCookie.Expires = DateTime.MinValue;

If your cookie is new one. The default value for DateTime should be DateTime.MinValue and no need to set.

CallMeLaNN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top