Skip to content

Instantly share code, notes, and snippets.

@HugoVG
Created July 23, 2022 14:23
Show Gist options
  • Save HugoVG/621a4fa956b557447e1e3de15d521c1f to your computer and use it in GitHub Desktop.
Save HugoVG/621a4fa956b557447e1e3de15d521c1f to your computer and use it in GitHub Desktop.
Identity framework, logging in and registering with Username instead of email
//Replace Email
<div class="form-floating">
<input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true" />
<label asp-for="Input.Email" class="form-label"></label>
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
//with everything under here
<div class="form-floating">
<input asp-for="Input.UserName" class="form-control" autocomplete="username" aria-required="true" />
<label asp-for="Input.UserName" class="form-label"></label>
<span asp-validation-for="Input.UserName" class="text-danger"></span>
</div>
public class InputModel
{
//Replace the email and the Email attribute and replace it with the Username field
[Required]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
//In public async Task<IActionResult> OnPostAsync(string returnUrl = null)
//Replace
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
//With
var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: false);
//Inside the form add above the email div this
<div class="form-floating">
<input asp-for="Input.Username" class="form-control" autocomplete="username" aria-required="true" />
<label asp-for="Input.Username"></label>
<span asp-validation-for="Input.Username" class="text-danger"></span>
</div>
//inside the InputModel
//add above the Email field
[Required]
[StringLength(20, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)]
[Display(Name = "Username")]
public string Username { get; set; }
//In public async Task<IActionResult> OnPostAsync(string returnUrl = null)
//Replace
await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
//With
await _userStore.SetUserNameAsync(user, Input.Username, CancellationToken.None);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment