Search code examples
c#asp.net-mvcasp.net-identity

IsEmailConfirmedAsync has some invalid arguments


I am using MVC 5's scaffold-ed code that generates a login method. I followed the official tutorial from...

Create a secure ASP.NET MVC 5 web app with log in, email confirmation and password reset (C#)

...to add the additional functionality of making sure email is confirmed before user can log in to the system.

The following is my code in the controller:

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

    var currentUser = UserManager.FindByNameAsync(model.Email);
    if (currentUser != null)
    {
        if (!await UserManager.IsEmailConfirmedAsync(currentUser.Id))
        {
            ViewBag.errorMessage = "You must have a confirmed email to log on.";
            return View("Error");
        }
    }

    // Other scaffolded implementations
}

However, Visual Studio comes up with an error that states that the argument is invalid for the method IsEmailConfirmedAsync. Apparently, I checked and the currentUser.Id is an int datatype and is the id for the System.Threading.Task. How do I fix this so that what I pass is the UserId instead of the Task Id?


Solution

  • That is because in your code currentUser is being assigned the Task returned from finding the user.

    You should await that call to get the desired behavior

    var currentUser = await UserManager.FindByNameAsync(model.Email);
    

    Even the example linked to the OP has it that way

    // Require the user to have a confirmed email before they can log on.
    var user = await UserManager.FindByNameAsync(model.Email);
    if (user != null)
    {
       if (!await UserManager.IsEmailConfirmedAsync(user.Id))
       {
          ViewBag.errorMessage = "You must have a confirmed email to log on.";
          return View("Error");
       }
    }