ergolargo
ergolargo

Reputation: 53

Default synchronization of Request.Cookies and Response.Cookies

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?

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

Answers (1)

Roman
Roman

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

Related Questions