6

I am creating a User using ASP.NET Core Identity as follows:

User user = new User {
  Email = "john@domain.com",
  Name = "John"
};            

await manager.CreateAsync(user, "JohnPass");

I get an error saying the Username is invalid because it is null.

How to configure Identity to use the Email as Username?

Or do I need to manually set the Username equal to the Email?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • I think your best bet is simply to set UserName to your email, with a custom UserValidator as shown here: http://stackoverflow.com/a/19460800/1166719 – Pierre-Loup Pagniez Oct 04 '16 at 08:50

1 Answers1

3

Use below code based on mandatory items

User user = new User {
  Id = id,// some auto generated id
  Email = "john@domain.com",
  UserName = "john@domain.com",// because you want to keep email id as UserName
  DisplayName= "John"
};            

await manager.CreateAsync(user, "JohnPass");

One potential issue with this approach is that if we keep email as 'User Name', then in some cases, it may not allow the user to change their email id in the future.

Gaurav P
  • 1,097
  • 1
  • 14
  • 19
  • 7
    Validation using this approach can be confusing to the user. If the user registers with an email that already exists, the error message from `UserManager.CreateAsync` says, "User name 'foo@bar.com' is already taken", even though the user has no concept of a user name. – Edward Brey Mar 10 '18 at 02:26