0

I'm trying to modify the value of my cookie but It doesn't modify instead it appends. What am I doing wrong?

Currently, SkillId cookie contains 112 in value, I want to update its value with whatever is in my variable qualifyBySkill.

string qualifyBySkill = "189";
HttpCookie cookie = Request.Cookies["SkillId"];
if (cookie != null)
{
    cookie.Values["SkillId"] = qualifyBySkill;
}
cookie.Expires = DateTime.UtcNow.AddDays(1);
Response.Cookies.Add(cookie);

What happens is, after this code it sets 112&SkillId=189 instead of 189 in Value. What am i doing wrong?

Huma Ali
  • 1,759
  • 7
  • 40
  • 66

1 Answers1

3

When thinking about cookies, it's helpful to remember that cookies are created by and stored by the browser alone. They are not passed back and forth between the browser and the server.

Request.Cookies contains a list of cookie headers that the browser sent, informing the server of the existence of a subset of cookies; they are not the actual cookies, and in fact lack much of the information contained in normal cookie record (e.g. domain and path).

Response.Cookies contains only set-cookie headers, asking the browser to create a cookie. This list is usually empty.

To change a cookie on the browser, the server must set a new cookie header. The important word being new.

string qualifyBySkill = "189";
var cookie = new HttpCookie("SkillId", qualifyBySkill);
cookie.Expires = DateTime.UtcNow.AddDays(1);
Response.Cookies.Add(cookie);
John Wu
  • 50,556
  • 8
  • 44
  • 80