如何在ASP上获得会话IsPersistent.净MVC

本文关键字:会话 IsPersistent MVC ASP | 更新日期: 2023-09-27 18:15:50

我有ASP。asp.net MVC 5.0项目使用ASP。净的身份。当用户登录时,使用此功能通过系统跟踪用户。

SignInManager.SignIn(user,IsPersistent,false)

在用户配置文件中,我有能力改变UserName,之后我需要自动重新登录用户以保持用户跟踪。我注销用户并使用此功能登录,但我在哪里可以获得当前会话的IsPersistent属性?

我可以在每次登录后在数据库的User表中存储IsPersistent,但我认为这不是最好的解决方案。

如何在ASP上获得会话IsPersistent.净MVC

我已经更改了AccountController的Login动作中的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, model.RememberMe, 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;
}

希望这能解决你的问题。

获取IsPersistent的值,调用AuthenticateAsync:

@using Microsoft.AspNet.Identity;
var authenticateResult = await HttpContext.GetOwinContext()
                               .Authentication.AuthenticateAsync(
                                   DefaultAuthenticationTypes.ApplicationCookie
                               );
var isPersistent = authenticateResult.Properties.IsPersistent; //// true or false