我使用带有身份和实体框架核心的asp.net core 2.0的web应用程序。我在创建数据库后尝试创建少数用户。我创建了从Program.Main()
调用的DbInitializer类 public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<ApplicationDbContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
}
}
host.Run();
}
问题是我无法访问我班级中的UserManager whit right PasswordHasher。我试试这个answer,我就像这样创建了新的UserManager
var store = new UserStore<ApplicationUser>(context);
var hasher = new PasswordHasher<ApplicationUser>();
var manager = new UserManager<ApplicationUser>(store, null, hasher, null, null, null, null, null, null);
await manager.CreateAsync(user, "password");
然后我创建用户。用户已创建,我可以在DB中看到他,问题是我无法使用给定的密码登录。我认为问题是我创建了新的PasswordHasher。如何访问应用程序中使用的UserManager?..
答案 0 :(得分:1)
我在尝试将用户播种到我的数据库时遇到了类似的问题,这就是我如何解决它。
尝试将服务而不是上下文传递给Initialize方法:
DbInitializer.Initialize(services);
然后更新Initialize方法:
public static void Initialize(IServiceProvider services) {
var context = services.GetRequiredService<ApplicationDbContext>();
//Do stuff with context
//Obtain reference to UserManager
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
// Set properties for new User
ApplicationUser user = new ApplicationUser
{
UserName = "admin@myapp.local",
Email = "admin@myapp.local"
};
//Set password
string password = "Change.Me99";
//Create new user
var result = userManager.CreateAsync(user, password);
//Check the result
}