8

I've got a cookie that I'm using to persist a user's userid but I'm having a hard time replacing it with a new value. According to MSDN, I should be able to simply overwrite the value, but it hasn't been working. I'm doing the login logic in a handler and passing the user on to a new webpage if they succeed.

public void ProcessRequest(HttpContext context)
{
    User user = User.FindByUsernameAndPassword(
        context.Request.Form["username"],
        context.Request.Form["password"]);

    context.Response.Cookies["user_id"].Value = user.ID.ToString();

    context.Response.Redirect("/profile", true);
}

The first time I log in it works well, but if I try to overwrite my current cookie by hitting the handler with a new user id, it doesn't change the cookie value and I continue to be logged in as the user I was when I hit it.

Other pages use the cookie to log in, but because the user id isn't changing it doesn't change the logged in user.

public User User { get; set; }

public override void Page_Load()
{
    this.User = User.Find(int.Parse(Request.Cookies["user_id"].Value));
}
Kyle Sletten
  • 5,365
  • 2
  • 26
  • 39

2 Answers2

6

Try adding .Value

context.Response.Cookies["user_id"].Value = user.ID.ToString();
Jakub Šturc
  • 35,201
  • 25
  • 90
  • 110
carlbenson
  • 3,177
  • 5
  • 35
  • 54
  • Sorry, that was actually a typo. The code won't even compile if you do it without the `.Value`. – Kyle Sletten Jun 10 '11 at 03:07
  • 1
    do we need to check if cookie exist before modifying its value,In other words will it error if cookie doesnt exist and we try to modify the value of a cookie which does not exist ? – sajanyamaha Apr 18 '13 at 13:25
  • yes, if the cookie is null, you can't access its Value property – carlbenson Apr 18 '13 at 14:59
4

According to the MSDN site, you have write a new cookie with the same name, not just modify it:

Modifying and Deleting Cookies

You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client. The following code example shows how you can change the value of a cookie that stores a count of the user's visits to the site:

int counter;
if (Request.Cookies["counter"] == null)
    counter = 0;
else
{
    counter = int.Parse(Request.Cookies["counter"].Value);
}
counter++;

Response.Cookies["counter"].Value = counter.ToString();
Response.Cookies["counter"].Expires = DateTime.Now.AddDays(1);

I'd agree with the first post about adding the .Value property and then maybe add the .Expires as well and see what happens.

Rob
  • 1,390
  • 1
  • 12
  • 25
  • do we need to check if cookie exist before modifying its value,In other words will it error if cookie doesnt exist and we try to modify the value of a cookie which does not exist ? – sajanyamaha Apr 18 '13 at 13:25