Answers
Jul 19, 2006 - 06:39 PM
you use the Request.Cookies collection to check if a cookie is on the users machine. You create a Cookie adding it to the Response.Cookies collection. The Cookie handling is a bit strange in ASP.NET 1.x. It seems that if you access Request.Cookies, all Cookies from Response.Cookies get copied over to Request.Cookies. So checking for an existing cookie using Request.Cookies is ok. If you add a cookie, use Response.Cookie. If you want to access this cookie, use Request.Cookie and the new cookie gets copied over. Confusing? You bet!
You shouldn't (or bette you can't easily) delete a cookie. A cookie gets removed from the clients machine if it expires. Set the Expires proprty of the cookie to now:
Response.Cookies["TheCookie"].Expires = DateTime.Now;
The operating system should clean out the expired cookie.
Hope this helped
Peter
Jul 21, 2006 - 05:27 PM
Peter got most of the cookie stuff correct. Just an augmentation to what he put down for the expiration, I usually set the cookie to expire one day ago, just to make sure that it cant be used: Response.Cookies["myCookies"].Expires = DateTime.Now.AddDays(-1);
You can remove values in the cookie, as well.
Let's say you've got a cookie and one of the keys is "foo" with the value of "bar"
myCookie.Values.Add("foo", "bar");
Once you're read in the cookie (using Request.Cookies as Peter shows above) you can remove the value for "foo".
myCookie = Requst.Cookies["theCookie"];
myCookie.Values.Remove("foo");
now, you've got to add the cookie back into the Cookie collection:
Response.Cookies.Add(myCookie);
If you want to see what is contained in the cookie now you can use:
Response.Write(myCookiesValues.ToString());
Have fun...
Ric
Jul 24, 2006 - 12:59 AM
I "fat-fingered" the last statement in my post above...not enough coffee, I guess.
It should read:
Response.Write(myCookie.Values.ToString());
That'll work much better...
Ric
Jul 24, 2006 - 10:59 PM
I'm surprised it's not more intuitive to do, but well now I've learned it :)
Feb 18, 2007 - 08:14 AM
Setting and reading cookies is a dialog between the server and the client.
When setting a cookie, the server adds it to the response headers and when the browser reads the headers, it should set the cookie accordingly. Therefore, always use the Response collection to set them.
Next time the client requests a page on your domain, it will add the (unexpired) cookies for that domain to the request headers, which will then be read by your server script (the Request collection).
The reason why cookies reasonably could copied from Response to Request automatically is that otherwise the cookie would still show as unset, even though you have just set it, until the user hits the next page or refreshes the current. But actually it kind of cheating when the server does this :-)
Jakob
Add New Comment