views:

1052

answers:

3

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!

+3  A: 

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.

Andrew Robinson
It looks like not setting an expiration (in the response headers) has the same effect?
Shawn Simon
I haven't tested that so I can't say for sure. Just recently spent a lot of time dealing with a cookie library for our project framework. Personally I prefer fruit these days.
Andrew Robinson
I would be glad to share the library at some point.
Andrew Robinson
+4  A: 

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";
Guffa
A: 

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

CallMeLaNN