Change cookie value in HttpHandler

I have a cookie that I use to save a user id, but it's hard for me to replace it with a new value. According to MSDN, I should just overwrite the value, but it does not work. I make a login to the handler and pass the user to a new web page 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 it logs in, it works well, but if I try to overwrite my current cookie by clicking on the handler with a new user ID, it will not change the cookie value, and I will continue to log in as a user I was when I got there.

Other pages use cookies to log in, but since the user ID does not change, it does not change the registered user.

 public User User { get; set; } public override void Page_Load() { this.User = User.Find(int.Parse(Request.Cookies["user_id"].Value)); } 
+7
source share
2 answers

Try adding .Value

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

According to the MSDN website, you are writing a new cookie with the same name, and not just changing it:

Modify and delete cookies

You cannot modify a cookie directly. 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 with the client. The following code example shows how you can change the value of the cookie that stores the user’s visit count on 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 agree with the first post about adding the .Value property, and then maybe add .Expires, and see what happens.

+4
source

All Articles