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));
}
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. Cookie received in request can have different properties than cookie previously send to browser.
To update a cookie, simply overwrite its value in the cookie object. You do this by setting a new cookie on the document with the same Name, but a different Value.
To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.
Try adding .Value
context.Response.Cookies["user_id"].Value = user.ID.ToString();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With