How do i set cookie expire time in C#
How do I set cookie expiration time in C#?
I want cookies to expire when the browser is closed. I found in many blogs that giving a previ开发者_JAVA百科ous date as the expiry date will cause the cookie to automatically expire, but that is not working in my case.
Hii bhasker,
The simple answer for your question is, do not explicitly specify cookie expiry time at the time of creation of a cookie. Then it will expire when the session is completed or the browser is closed.
You also have to close all other pages from the same browser, for example if you are using firefox, you have a process nameed firefox.exe which will not end until last window is open and session wil not expire
Why not use session instead of a specific time on the cookie? That way, when you close the browser, the session will also end, expiring the cookie.
var cookie = new HttpCookie("name", "value")
{
HttpOnly = true
};
Don't set the Expires property or you will get a persistent cookie surviving browser restarts.
Setting the expiry date to a previous date will cause the cookie to be deleted, it does "NOT" make it automatically expire.
Let's say the browser is storing a cookie that has an expiry date set to tomorrow. When you change the cookie expiry date to yesterday, the browser sniffs it and says "this is expired, I'm gonna toss it", effectively deleting the cookie (in fact there's no other way to delete a cookie).
If you don't set an expiry time when the cookie is created, and don't edit that property, the cookie automatically becomes a session cookie, causing the cookie to be deleted when the user closes the browser.
HttpContext.Response.Cookies.Append("cookieName", "cookieValue", new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(1) });
精彩评论