Not so tasty cookies

Thursday, Sep 11, 2008 2 minute read Tags: generic .net rant
Hey, thanks for the interest in this post, but just letting you know that it is over 3 years old, so the content in here may not be accurate.

As a general rule I'll avoid web cookies, they've got a bad wrap, and are too often used and abused.

But for storing long life information on a client there's not really anything better.

So recently I was putting them into a site which would check when you first hit it if the cookie exists, if it didn't then create it. Having not used cookies for a while I'd lost touch with how they operate, especially in the ASP.NET collection.

Since HttpCookieCollection is a named collection you'd think that you could just got:

HttpCookie myCookie = Response.Cookies["myCookie"];

Well you can... sort of, I'll get to the sort of shortly, but some background.
Every time I did this I ended up with a cookie, regardless of whether one already existed or not. If it didn't exist then it'd have an expiry equal to DateTime.MinDate. Fine, what ever, I can detect that, so I had a handler to check that condition as well as a null return in myCookie.

Then I have the following lines:

HttpCookie myRealCookie = new HttpCookie("myCookie");
myRealCookie.Value = "something";
myRealCookie.Expiry = DateTime.Now.AddDays(1);


But when I hit the control that is to use the cookie I get back the first "dud" cookie. WTF?
So I look at the HttpCookieCollection, low-and-behold I have 2 cookies named "myCookie". And when I try and get one out I always get the dud cookie.

So I fire up Reflector and look squarly at what happens and this is what I found:

			public HttpCookie this[string name]{    
				get    {        
					return this.Get(name);    
			}public HttpCookie Get(string name){    
				HttpCookie cookie = (HttpCookie) base.BaseGet(name);    
				if ((cookie == null) && (this._response != null))    {        
					cookie = new HttpCookie(name);        
					this.AddCookie(cookie, true);        
				return cookie;

Oh you have to be kidding me. You'd think that when I try and get a cookie that may not exist it doesn't just add the frigging thing!

So then I had to implement a lovely work around to itterate through the collection, check them by their index.
Hello performance!

Yes, this is just another lovely example of the .NET framework thinking we're too dumb to handle coding ourselves.