Hi,
After I create or modify a httpcookie, do I have to do add it to the response.cookies collection? (if yes, only if its a new cookie or even if I am modifying one)
Hi,
After I create or modify a httpcookie, do I have to do add it to the response.cookies collection? (if yes, only if its a new cookie or even if I am modifying one)
If it is new it needs to be added to the Response.Cookies collection to be stored, but you can access the collection like an array.
Response.Cookies["foo"] = myCookie;
This will take care of the adding for you. FYI, if the cookies has not been created the value will return null.
However the cookie will be updated if you refer to the collection like this:
HttpCookie myCookie = Response.Cookies["foo"];
Any modifications to myCookie will be made to the cookie in the collection because in C# when you assign a variable to an existing class object, that object is handled by reference and it is modified.
If you don't add a cookie to the Response.Cookies collection, it will never be sent to the browser. However, once you add the cookie to the collection, you can modify it as you please and the last value you set is what will be sent to the browser. What you are adding to the collection is a reference to your HttpCookie object, and the cookie is not sent to the browser until the end of the request life cycle.