views:

218

answers:

3

The following code will send a cookie to the user as part of the response:

var cookie = new HttpCookie("theAnswer", "42");
cookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(cookie);

The cookie is of the persistent type, which by most browsers will be written to disk and used across sessions. That is, the cookie is still on the client's PC tomorrow, even if the browser and the PC has been closed in between. After a week, the cookie will be deleted (due to line #2).

Non-persistent/in-memory cookies are another bread of cookies, which have a lifespan determined by the duration of the client's browsing session. Usually, such cookies are held in memory, and they are discarded when the browser is closed.

How do I assign an in-memory cookie from ASP.NET?

+9  A: 

Just omit the expiration date. By not setting a value the cookie will automatically be discarded after the session is over.

var cookie = new HttpCookie("theAnswer", "42");
Response.Cookies.Add(cookie);
Bob
This is not even ASP.NET specific. Non-persistent cookies are, by definition, the ones without an expiration date. :)
bzlm
I actually suspected this to be the answer, but a few quick searches on Google and SO turned up no credible sources. At least now it's documented here! @bzlm: thanks for the bonus info, didn't know that :)
Jørn Schou-Rode
So, the shorthand version `Response.Cookies["theAnswer"].Value = "42"` would also result in a non-persistent cookie, right?
Jørn Schou-Rode
Yeah that should work too. According to MSDN it will create the cookie if it doesn't exist when you access it that way.
Bob
+3  A: 

If you don't specify expiration at all, then it makes the kind of cookie you're asking for.

MikeBaz
A: 

assigning DateTime.MinValue to the expiration also does the trick...

Tim Mahy