Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpCookieCollection.Add vs HttpCookieCollection.Set - Does the Request.Cookies collection get copied to the Response.Cookies collection?

Tags:

I just want to clear this up.

I know that if I have set a cookie on a previous request, it will show up in my Request.Cookies collection.

I want to update my existing Cookie.

Are the cookies from my Request.Cookies collection already copied to my Response.Cookies collection? Do I need to add a new cookie with the same key using Response.Cookies.Add(), or do I need to use Response.Cookies.Set()?

like image 482
smartcaveman Avatar asked Apr 01 '11 18:04

smartcaveman


People also ask

What is the difference between request cookies and response cookies?

Response cookies are cookies that you want the browser to set on the client machine. Request cookies are cookies that already exist on the client side and have been sent by the browser together with the request.

How do you add cookies to a response?

To add a new cookie, use HttpServletResponse. addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction. Btw, I don't recommend you do this to create your own authentication scheme.

How do cookies work in asp net?

Cookies provide a means in Web applications to store user-specific information. For example, when a user visits your site, you can use cookies to store user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier.

Which object S contains the cookies collection in an ASP NET MVC web application?

ASP.NET includes two intrinsic cookie collections. The collection accessed through the Cookies collection of HttpRequest contains cookies transmitted by the client to the server in the Cookie header.


1 Answers

There is a difference:

  • Response.Cookies.Add() will allow duplicate cookies to be set http://msdn.microsoft.com/en-us/library/system.web.httpcookiecollection.add.aspx
  • Response.Cookies.Set() will make sure the cookie is unique by first checking to ensure the cookie doesn't exist http://msdn.microsoft.com/en-us/library/system.web.httpcookiecollection.set.aspx

Duplicate cookies typically requires extra handling to determine which is the most recent. I'm not sure of a case when you would want duplicate cookies on the same site, maybe someone else can chime in with an example

Edit: In your case, you want to use set because you are updating.

like image 120
Prescott Avatar answered Oct 02 '22 20:10

Prescott