Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net HttpCookie class / session cookie questions

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!

like image 653
Shawn Avatar asked Mar 10 '09 15:03

Shawn


2 Answers

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";
like image 119
Guffa Avatar answered Oct 21 '22 05:10

Guffa


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.

like image 24
andleer Avatar answered Oct 21 '22 05:10

andleer