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

MVC Identity, enable UserName, but login breakes


I want the user to add their names to the application(and I am successful in storing it) and keep login in with their email. But when login in I get "Invalid login attempt" and I am clueless as to why...

In the model(AccountViewModel) I added Name:

[Required]
public string Name { get; set; }

In AccountController I made the following changes to store the value on registration

var user = new ApplicationUser {
    UserName = model.Name,
    Email = model.Email
};

And in Register.cshtml added a field to store their name

<div class="form-group">
    @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
    </div>
</div>

The only changes I made was to the UserName and not the Email. As the login uses the email I am not sure why the login should be affected..

// POST: /Account/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);
    }
}

Solution

  • The UserName that you are using as the model name is the one used for identity authentification not the Email. In this case you probably need to create a new field to store your name.