Login with User Name instead of Email in ASP.NET MVC Identity

ASP.NET MVC

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.

View Models
View Models

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
  1. Posted by Johnd734
  2. Posted by reklama

Leave a Reply

Your email address will not be published.