开发者

Modifying a Cookie's Value in a HttpHandler

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.Coo开发者_如何学Ckies["user_id"].Value));
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜