Reputation: 53
Would it be possible for anybody to clarify the behaviour I am experiencing in a .NET 4.0 web app, when trying to manipulate the cookie collections in Response.Cookies and/or Request.Cookies. Despite my efforts to find documentation or forum postings to explicitly confirm the expected default behaviour of Request.Cookies and Response.Cookies, I have never been able to find a definitive answer, and I have now encountered a situation where I need to!
My exact questions would be: * Are Request.Cookies and Response.Cookies definitely supposed to be thought of as entirely separate collections, or do they actually represent two different 'views' of the same collection?
To what degree is there synchronization built into the 'relationship' between Request.Cookies and Response.Cookies. Apart from the fact that a cookie added to Response.Cookies is immediately visible in Request.Cookies, which I know about because it has been documented, should I by default be expecting all the other cookies in the two collections to always be the same due to additional automatic syncing?
If there is some synchronization, is it instantaneous, or is it all handled at some particular stage in the life cycle?
If there is some synchronization, is it possible, or even advisable, to avoid it occurring?
What is the best way of handling duplicate cookies from previous stale browser requests? At the moment, my efforts to do so are not successful, as any changes I make to the Response.Cookies are immediately included in Request.Cookies (that expected behaviour again), BUT then ... some implicit 'phantom' process occurs which has the result of synchronizing the collections again - in other words, the only possible outcomes I can find are for my Response.Cookies collection to have no copies of the duplicate cookie, or be returned back to its original state of two duplicate cookies.
Obviously from the last question, I am clearly misunderstanding the default behaviour of these two collections. That is why any clarification of what SHOULD happen would be very gratefully received!
Thanks in advance ...
Upvotes: 1
Views: 677
Reputation: 1217
The Request and Response object's Cookies property are two distinct instances of the HttpCookieCollection. However, when a Response object is initialized, the instance of the HttpCookieCollection is created with a reference of the Response object.
Calls to the Response.Cookies.Add will add a cookie not only self instance but also to the Request.Cookies as well, via Response.OnCookieAdd(cookie).
Overall, you would want to follow the practice of grabbing a cookie out of the Request.Cookies and either timeout (removing the cookie on the browser) or modifying it and then setting it back to the Response. If you want to just add the cookie then use the Add method otherwise use Set to ensure only one cookie by that name is returned. See the other post.
Upvotes: 1