如果您想手动添加用户,则还应设置NormalizedUserName
属性。此外,最好使用IPasswordHasher<TUser> Interface
来散列密码:
注入的服务:
private readonly ApplicationDbContext _context;
public readonly IPasswordHasher<IdentityUser> _passwordHasher;
public HomeController( ApplicationDbContext dbContext, IPasswordHasher<IdentityUser> _passwordHasher)
{
this._context = dbContext;
this._passwordHasher = _passwordHasher;
}
我假设你的User
继承了IdentityUser
,这里我以IdentityUser
为例:
IdentityUser applicationUser = new IdentityUser()
Guid guid = Guid.NewGuid()
applicationUser.Id = guid.ToString()
applicationUser.UserName = "Joe"
applicationUser.Email = "wx@hotmail.com"
applicationUser.NormalizedUserName = "wx@hotmail.com"
_context.Users.Add(applicationUser)
var hashedPassword = _passwordHasher.HashPassword(applicationUser, "YourPassword")
applicationUser.SecurityStamp = Guid.NewGuid().ToString()
applicationUser.PasswordHash = hashedPassword
_context.SaveChanges()
您还可以使用 UserManager.CreateAsync
来使用指定的密码在后备存储中创建指定的用户:
var user = new IdentityUser { UserName = "Joe", Email = "wx@hotmail.com" };
var result = await _userManager.CreateAsync(user, "YourPassWord");
if (result.Succeeded)
{
}
注意:登录时应提供电子邮件
值。