ASP.NET Core : How to login with “UserName” instead of “Email”?

The first step is to scaffold identity to your application :

Scaffold Identity in ASP.NET Core projects

Then you could customize the Register.cshtml/Register.cshtml.cs and Login.cshtml/Login.cshtml.cs , update model and view , and change the logic in OnPostAsync function to fit your requirement .

To your requirement , you can follow the steps :

  1. Scaffold identity into your project .
  2. Modify the Register.cshtml.cs , add Username to InputModel :

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "User Name")]
    public string UserName { get; set; }
    
  3. Modify the OnPostAsync method :

    var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
    
  4. Update the Register.cshtml to include the UserName :

    <div class="form-group">
        <label asp-for="Input.UserName"></label>
        <input asp-for="Input.UserName" class="form-control"/>
        <span asp-validation-for="Input.UserName" class="text-danger"></span>
    </div>
    
  5. Modify the Login.cshtml.cs , modify InputModel to replace Email with UserName :

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "User Name")]
    public string UserName { get; set; }
    
  6. Modify the Login.cshtml :

    <div class="form-group">
        <label asp-for="Input.UserName"></label>
        <input asp-for="Input.UserName" class="form-control" />
        <span asp-validation-for="Input.UserName" class="text-danger"></span>
    </div>
    
  7. Modify the Login.cshtml.cs OnPostAsync method to use Username instead of email :

    var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
    

By default ASP.NET Identity uses FindByNameAsync to check if user with given name exists , so that you don't need to override PasswordSignInAsync function in SignInManager . If you want to login with email , your could click here to update that .


When using the excepted answer I also had to modify the following line in step three from Input.Email to Input.UserName on the latest ASP.NET Core template.

await _userStore.SetUserNameAsync(user, Input.UserName, CancellationToken.None);