c# – 如何获得ASP.NET MVC上的会话IsPersistent?
发布时间:2020-12-15 22:36:41 所属栏目:百科 来源:网络整理
导读:我使用ASP.NET身份的ASP.NET MVC 5.0项目.当用户登录时,我使用此功能按系统跟踪用户. SignInManager.SignIn(user,IsPersistent,false) 在用户配置文件中,我有能力更改UserName,之后我需要自动重新登录用户以保持用户跟踪.我注销用户并使用此功能登录,但我可
我使用ASP.NET身份的ASP.NET MVC 5.0项目.当用户登录时,我使用此功能按系统跟踪用户.
SignInManager.SignIn(user,IsPersistent,false) 在用户配置文件中,我有能力更改UserName,之后我需要自动重新登录用户以保持用户跟踪.我注销用户并使用此功能登录,但我可以在哪里获得当前会话的IsPersistent属性? 我可以在每次登录后将IsPersistent存储在数据库的User表中,但我认为这不是最好的解决方案. 解决方法
我在AccountController的Login操作中更改了登录代码以满足您的要求.我已经注释掉了ASP.NET Identity默认登录机制.
现在这段代码的作用是首先找到用户,然后检查输入的密码是否与用户密码匹配.一旦密码匹配,它将向用户添加虚假声明以存储持久状态并登录用户. [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model,string returnUrl) { if (!ModelState.IsValid) { return View(model); } SignInStatus result = SignInStatus.Failure; var user = UserManager.FindByEmail(model.Email); if (user != null) { var isPasswordOk = UserManager.CheckPassword(user,model.Password); if (isPasswordOk) { user.Claims.Add(new IdentityUserClaim() { ClaimType = "IsPersistent",ClaimValue = model.RememberMe.ToString() }); await SignInManager.SignInAsync(user,model.RememberMe,false); result = SignInStatus.Success; } } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout,change to shouldLockout: true //var result = await SignInManager.PasswordSignInAsync(model.Email,model.Password,shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode",new { ReturnUrl = returnUrl,RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("","Invalid login attempt."); return View(model); } } 用户登录后,您可以使用以下代码检查用户是否持久. if (User.Identity.IsAuthenticated) { Claim claim = ((ClaimsIdentity)User.Identity).FindFirst("IsPersistent"); bool IsPersistent = claim != null ? Convert.ToBoolean(claim.Value) : false; } 我希望这能解决你的问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |