问题描述
我想做的是添加一个新的管理员用户,并为其分配管理员角色.所以..我进入了Configure
方法中的Startup.cs
类,并编写了以下代码:
What I'm trying to do is to add a new admin user and assign it with the admin role.So.. I went to the Startup.cs
class in Configure
method and wrote the following code:
var context = app.ApplicationServices.GetService<ApplicationDbContext>();
// Getting required parameters in order to get the user manager
var userStore = new UserStore<ApplicationUser>(context);
// Finally! get the user manager!
var userManager = new UserManager<ApplicationUser>(userStore);
但是,我收到以下错误消息:
However, I get the following error message:
此错误在这里使我丧命..显然,我需要userManager来创建新用户,但我无法初始化该东西.
This error is killing me here.. obviously I need the userManager in order to create the new user but I just can't initialize this thing.
推荐答案
您可以使用依赖注入来获取UserManager的实例.只需向configure方法添加一个参数,就像这样:
You can use dependency injection to obtain an instance of UserManager. Just add a parameter to the configure method, like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
然后,您可以创建用户和角色.我通常将此代码移到静态类中.
Then you can create users and roles. I usually move this code into a static class...
public static class DbInitializer
{
public static async Task Initialize(ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
// Ensure that the database exists and all pending migrations are applied.
context.Database.Migrate();
// Create roles
string[] roles = new string[] { "UserManager", "StaffManager" };
foreach (string role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
await roleManager.CreateAsync(new IdentityRole(role));
}
}
// Create admin user
if (!context.Users.Any())
{
await userManager.CreateAsync(new ApplicationUser() { UserName = "info@example.com", Email = "info@example.com" }, "p@ssw0rd");
}
// Ensure admin privileges
ApplicationUser admin = await userManager.FindByEmailAsync("info@example.com");
foreach (string role in roles)
{
await userManager.AddToRoleAsync(admin, role);
}
}
}
...并在Startup.Configure方法中调用该方法:
... and call the method in the Startup.Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
// Code omitted for brevity
// Create seed data
DbInitializer.Initialize(context, userManager, roleManager).Wait();
}
在Entity Framework Core的下一版本中,数据库种子将是添加为功能.
In one of the next releases of Entity Framework Core database seeding will be added as a feature.
这篇关于无法获取UserManager类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!