c# – 如何获得ASP.NET MVC上的会话IsPersistent?

我使用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, 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;
}

我希望这能解决你的问题.

点赞