Skip to content

11 Username Instead of Email

M. Fares edited this page Mar 12, 2018 · 1 revision

How to login with UserName instead of Email address?

  1. In /Models/AccountViewModels/LoginViewModel class Comment the following code
//[Required]
//[Display(Name = "Email")]
//[EmailAddress]
//public string Email { get; set; }

Add the following code

[Required]
[Display(Name ="User Name")]
public string UserName { get; set; }
  1. In /Models/AccountViewModels/RegisterViewModels class Add the following code
[Required]
[Display(Name ="User Name")]
public string UserName { get; set; }
  1. In /Controllers/AccountController/Login (Post Action) Change the parameter mode.Email to model.UserName
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
  1. In /Controllers/AccountController/Register (Post Action) Change UserName = model.Email to UserName = model.UserName
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
  1. In /Views/Account/Login.cshtml Change all instances of Email to UserName

  2. In /Views/Account/Register.cshtml Add a new div for UserName before the Email div (Copy paste the Email div)

<div class="form-group">
    @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
    </div>
</div>
  1. In /Models/AccountViewModels/ForgotPasswordViewModel class Add the user name property in addition to the email
[Required]
[Display(Name = "User Name")]
public string UserName { get; set; }
  1. In /Controllers/AccountController/ForgotPassword() Change the if condition to the code:
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))
    || (await UserManager.GetEmailAsync(user.Id)) != model.Email)
  1. In /Views/Account/ForgotPassword.cshtml Add the following code before the email form
<div class="form-group">
    @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
    </div>
</div>
  1. Change any code you added such as view model classes, conrollers and views
  2. Test registration, login, and forgotPassword views

Clone this wiki locally