0
我使用ASP.net MVC4与SimpleMemberShip。Simplemembership登录和RemeberMe ASP.Net MVC4
我只是想存储用户名,如果记住我复选框勾选并重新从cookie中加载它。
登录工作正常,RememberMe设置为true。但Request.Cookies [FormsAuthentication.FormsCookieName]始终为空。我很困惑这应该如何工作。
登录控制器:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Index(LoginModel model, string returnUrl)
{
bool RememberMe = model.RememberMe == "on" ? true : false;
if (WebSecurity.Login(model.UserName, model.Password, persistCookie: RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
登录页面控制器:
[AllowAnonymous]
public ActionResult Index(string returnUrl)
{
// load user name
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
ViewBag.Username = Server.HtmlEncode(ticket.Name);
ViewBag.RememberMeSet = true;
}
else
{
ViewBag.RememberMeSet = false;
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
如果你只是想在当前登录用户的用户名,为什么不干脆用WebSecurity.CurrentUserName属性。 http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity.currentusername(v=vs.111).aspx – 2013-04-24 12:44:04
我只是想通过formsauthentication将cookie中存储的用户名加载到用户名文本框中在登录页面上。 – Simon 2013-04-24 16:50:48
如果您尝试在登录页面上使用它,那么我假定该用户未登录。如果他们未登录,则该Cookie将为空。如果他们已经登录,那么你正在尝试做的工作。但是,如前所述,如果他们登录,更容易调用WebSecurity.CurrentUserName来获取用户名,而不是试图从cookie中提取它。 – 2013-04-24 17:36:38