mandag den 14. december 2009

Cookies in ASP.NET

I always find myself struggling with Cookies in asp.net.

I always fail to add the cookies the right way or to remove them.
I always tend to open old projects to see how I coped then.
But most of the project are filled with different tries to get the cookie stuff to work so it doesnt help much.

There are three issues that we are dealing with

1. Adding a cookie that never expires
2. Adding a cookie that expires with a day or so
3. Removing a cookie

1 + 2. The first mistake I make is trying to add a cookie to the Request.Cookie collection which obviously doesnt work due to the fact it is a collection comming from the server.

All cookie should be added to the Response.Cookie collection.
For adding expiration you just set the Expire property on the HttpCollection before adding the cookie. For a cookie that never expires you set Expire = DateTime.MaxValue;

3. Removing a cookie is not done "just" by removing the cookie from the request cookie collection. You also need to add a new cookie with the same name as the one you want to remove and setting Expire to yesterday to Response.Cookie collection . This forces the cookie to expire the next time the client requests the page.

 HttpCookie c = new HttpCookie(CookieName, "false");  
 c.Expires = DateTime.Now.AddDays(-1);  
 Response.Cookies.Add(c);  
 Request.Cookies.Remove(CookieName);   

Very simple but a hell of a job if you forget just one of them.

Ingen kommentarer:

Send en kommentar