为什么signinmanager.passwordsigninasync方法在MVC5中一直返回失败

时间:2017-11-01 15:00:20

标签: c# asp.net-mvc-5

这是我的Login方法:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
   if (!ModelState.IsValid)
   {
       return View(model);
   }
   //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);
   }
}

这是我的授权过滤器:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    var userEmailId = httpContext.Session["userName"];
    bool authorize = false;
    foreach (var role in allowedroles)
    {
        /* getting user form current context */
        var user = context.employees.Where(m => m.emailId == userEmailId  && m.Role == role);
        if (user.Count() > 0)
        {
            authorize = true; /* return true if Entity has current user(active) with specific role */
        }
    }
    return authorize;
}

这是我的行动方法:

[AuthAttribute]
[CustomAuthorize("Admin", "SuperAdmin")]
public ActionResult GetEmployeeList(string sortOrder, string currentFilter, string searchString, int? page)
{
    return View(db.GetListviewData().ToList());
}

我尝试使用授权过滤器来检查数据库中的用户角色但是当我尝试登录我的应用程序SignInManager.PasswordSignInAsync时,每次都返回失败。

请提前帮助我

1 个答案:

答案 0 :(得分:0)

我有同样的问题,但我意识到它只发生在用户更改了他们的电子邮件之后(显然UserName不再等于电子邮件)。

看一下PasswordSignInAsync的签名,第一个参数是UserName,但Visual Studio项目模板的默认代码包含了你和我都拥有的东西,Email。

变化:

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

要:

var result = await SignInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, shouldLockout: false);