Naved Nakedar
Naved Nakedar

Reputation: 11

Change ASP .NET CORE Identity default email address under the Username column

ASP .NET CORE Identity stores email address as default under the Username column. How do i change it from storing the email address as a Username to a custom name as a username ?

Upvotes: 1

Views: 654

Answers (3)

Darshani Jayasekara
Darshani Jayasekara

Reputation: 741

You can always change scaffolded register page to have both username field and email field. The model already have both.

More importantly if you willing to have separate username field you have to be more careful on places where you retrieve users by email address. If the email address is not unique, then you got to be in trouble if you do not pay attention to those places. Specially on pages like reset password page.

I faced a similar kind of situation. Our application originally built to have email as username. Therefore in the db both username and email were same. So throughout the application there were lot of pages where we retrieved user by email. Then client wanted to have non email usernames. After supporting it, reset password was not working, because email address was not unique and had multiple users with same email.

To fix the issue what I could do is change the reset password Uis or make email as unique field.

To make email unique in asp. Net core identity you can use options.User.RequireUniqueEmail = true; in identity service Startup.cs file.

Even though it is too late to answer this question, I thought to answer this today because this can be helpful to some one in 2021

Upvotes: 1

Ryan
Ryan

Reputation: 20106

When you scaffold Identity and register a user, the OnPostAsync handler in Register.cshtml.cs has following code to create the user which decides the value of UserName column.

var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);

You could cahnge UseName = Input.Email to your custom name.

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239220

This is just how the default UI handles it. If you want to do it another way, then you'll need to scaffold the Register page into your project and change it. Specifically, you're looking for this line in Register.cshtml.cs:

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

There, you'll simply change Input.Email to something like Input.UserName. Of course you'll need to add a UserName property to the page model so that you can collect this information in the first place, and add an input to the view accordingly.

Upvotes: 1

Related Questions