Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign a non-persistent (in-memory) cookie in ASP.NET?

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?

like image 736
Jørn Schou-Rode Avatar asked Nov 24 '09 13:11

Jørn Schou-Rode


1 Answers

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);
like image 90
Bob Avatar answered Sep 19 '22 05:09

Bob