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