C#:UserManager.FindAsync总是找到匹配项

时间:2016-05-05 11:57:24

标签: c# .net authentication

即使我输入了错误的用户名和密码,

UserManager.FindAsync总会找到匹配项,但它总是会返回某种用户ID。

[HttpPost]
public ActionResult Mobilelogin(LoginViewModel model)
{
    var user = UserManager.FindAsync(model.Email, model.Password);
    if (user != null)
    {
        return new HttpStatusCodeResult(201); // user found
    }
    else
    {
        return new HttpStatusCodeResult(401); // user not found
    }
}

1 个答案:

答案 0 :(得分:3)

FindAsync返回Task<TUser>。如果您同步使用它(正如您现在所做的那样),您将始终获得Task本身非空。

您需要异步等待任务才能获得结果(TUser),如下所示:

[HttpPost]
public async Task<ActionResult> Mobilelogin(LoginViewModel model)
{
    var user = await UserManager.FindAsync(model.Email, model.Password);
    if (user != null)
    {
        return new HttpStatusCodeResult(201); // user found
    }
    else
    {
        return new HttpStatusCodeResult(401); // user not found
    }
}

有关使用ASP.NET MVC进行异步编程的更多信息,请查看this reference