Login with User Name instead of Email in ASP.NET MVC Identity
When an ASP.NET MVC Application is created with “Individual Accounts” authentication, it is set to use Email address to Register and Sign in instead of User Name, so in this Post I’ll show how to use User Name to Register and Login.
Open AccountViewModels.cs in Models folder, add below code in LoginViewModel and RegisterViewModel
[Required] [Display(Name = "User Name")] public string UserName { get; set; }
So now ViewModels will look like this.
Open AccountController.cs
In Register method; replace
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
with
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
and in Login method; replace
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
with
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
Open Login.cshtml from View / Account, replace
<div class="form-group"> @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" }) </div> </div>
with
<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" }) @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" }) </div> </div>
Open Register.cshtml from View / Account, add below code after Email div block
<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>
Now run the website, and you’ll be able to Register and Login with User Name 🙂
Comments
Outstanding post, you have pointed out some fantastic points, I as well think this is a very great website.
Great goods from you, man. I've understand your stuff previous to and you are just too wonderful. I actually like what you have acquired here, certainly like what you are saying and the way in which you say it. You make it entertaining and you still care for to keep it smart. I can not wait to read far more from you. This is really a tremendous website.