ASP.Net MVC Cookies not persisting



基本上,我试图在用户登录后设置一个cookie,以便在下次登录时持久化他们的用户名。这是我设置cookie的代码。当我在Firefox中查看设置了cookie的站点cookie时,它显示的是sessionID cookie,而不是我刚刚设置的那个。当我检查Fiddler的header时,我没有看到它设置cookie,只有我的sessionID cookie。

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

我在这里检查cookie是否存在。

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

下面是所讨论的方法的完整上下文

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);
}

添加到响应中。

最新更新