Felix C Felix C - 3 months ago 49
ASP.NET (C#) Question

Difference between HttpResponse: SetCookie, AppendCookie, Cookies.Add

there are some different ways to create multi value cookies in ASP.NET:

var cookie = new HttpCookie("MyCookie");
cookie["Information 1"] = "value 1";
cookie["Information 2"] = "value 2";

// first way
Response.Cookies.Add(cookie);

// second way
Response.AppendCookie(cookie);

// third way
Response.SetCookie(cookie);


When should I use which way? I've read that
SetCookie
method updates the cookie, if it already exits. Doesn't the other ways update the existing cookie as well?

And is the following code best practice for writing single value cookies?

Response.Cookies["MyCookie"].Value = "value";

Answer

When should I use which way?

It's depends on what Cookie operation you want to do.

Note that Add and AppendCookie are doing the same functionality except the fact that with AppendCookie you're not referencing the Cookies property of the Response class and it's doing it for you.

  • Response.Cookies.Add - Adds the specified cookie to the cookie collection.
  • Response.AppendCookie - Adds an HTTP cookie to the intrinsic cookie collection
  • Response.SetCookie - Updates an existing cookie in the cookie collection.

Exceptions will not be thrown when duplicates cookies are added or when attempting to update not-exist cookie.

The main exception of these methods is: HttpException (A cookie is appended after the HTTP headers have been sent.)

The Add method allows duplicate cookies in the cookie collection. Use the Set method to ensure the uniqueness of cookies in the cookie collection.

Thanks for MSDN!

Comments