Search code examples
asp.netasp.net-mvcrazorasp.net-identity

How to login with "UserName" instead of "Email" in MVC Identity?


I need to set my login to use username instead of email address, how can I change it?


Solution

  • It's actually using the e-mail address as the username, so in the ASPNetUsers table, you'll see both the username and email fields with the email address.

    Go into the AccountController, look for Register method (POST).

    Change this:

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

    to this:

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

    Then go into the Login.cshtml and change all corresponding e-mail model fields to username instead.

    Finally, go into the Login method (POST) in the AccountController and change model.Email to model.UserName.

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

    You also have to make changes in AccountViewModels.cs in order to introduce your new UserName property.