[英]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.本质上,我试图在用户登录后设置一个 cookie,以便在下次登录时保留他们的用户名。这是我设置 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.
当我在设置 cookie 后立即查看 Firefox 中的站点 cookies 时,它会显示 sessionID cookie,但不是我刚刚设置的那个。 When I check the headers in Fiddler, I don't see it setting the cookie, only my sessionID cookie.
当我检查 Fiddler 中的标题时,我没有看到它设置了 cookie,只有我的 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.这是我检查cookie是否存在的地方。
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);
}
Add to response.cookies not request.cookies添加到响应。cookies 不是请求。cookies
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.