If you want to manually add the user , you should also set the NormalizedUserName property . In addition , it's better to use IPasswordHasher<TUser> Interface for hashing passwords:
The injected services :
private readonly ApplicationDbContext _context;
public readonly IPasswordHasher<IdentityUser> _passwordHasher;
public HomeController( ApplicationDbContext dbContext, IPasswordHasher<IdentityUser> _passwordHasher)
{
this._context = dbContext;
this._passwordHasher = _passwordHasher;
}
I assume your User inherits IdentityUser , here i use IdentityUser for example:
IdentityUser applicationUser = new IdentityUser();
Guid guid = Guid.NewGuid();
applicationUser.Id = guid.ToString();
applicationUser.UserName = "Joe";
applicationUser.Email = "[email protected]";
applicationUser.NormalizedUserName = "[email protected]";
_context.Users.Add(applicationUser);
var hashedPassword = _passwordHasher.HashPassword(applicationUser, "YourPassword");
applicationUser.SecurityStamp = Guid.NewGuid().ToString();
applicationUser.PasswordHash = hashedPassword;
_context.SaveChanges();
You can also use UserManager.CreateAsync to create the specified user in the backing store with given password :
var user = new IdentityUser { UserName = "Joe", Email = "[email protected]" };
var result = await _userManager.CreateAsync(user, "YourPassWord");
if (result.Succeeded)
{
}
Notice : You should provide Email value during login .