Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC Cookies not persisting

Essentially I'm trying to set a cookie after a user logs in to persist their username for the next time they log in. Here's my code to set the cookie. When I look at the site cookies in Firefox as soon as the cookie is set, it shows the sessionID cookie, but not the one I just set. When I check the headers in Fiddler, I don't see it setting the cookie, only my sessionID cookie.

HttpCookie hc = new HttpCookie("username", model.UserName);
hc.Expires = DateTime.Now.AddYears(1);
System.Web.HttpContext.Current.Request.Cookies.Add(hc);

Here is where I check to see if the cookie exists.

if (System.Web.HttpContext.Current.Request.Cookies["username"] != null)

Here's the full context of the methods in question

public ActionResult LogOn()
{
    if (System.Web.HttpContext.Current.Request.Cookies["username"] != null)
        return View(new LogOnModel { UserName = System.Web.HttpContext.Current.Request.Cookies["username"].Value });
    else
        return View();
}

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (MembershipService.ValidateUser(model.UserName, model.Password))
        {
            HttpCookie hc = new HttpCookie("username", model.UserName);
            hc.Expires = DateTime.Now.AddYears(1);
            System.Web.HttpContext.Current.Request.Cookies.Add(hc);

            FormsService.SignIn(model.UserName, model.RememberMe);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

    return View(model);
}
like image 483
Jhorra Avatar asked May 03 '11 22:05

Jhorra


1 Answers

Add to response.cookies not request.cookies

like image 68
Adam Tuliper Avatar answered Sep 19 '22 02:09

Adam Tuliper