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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With