【发布时间】:2019-09-23 10:23:46
【问题描述】:
我正在使用 asp.net core 2.2 默认网站模板和身份验证选择作为个人用户帐户。如何创建“管理员”角色并将其分配给用户,以便我可以使用控制器中的角色来过滤访问权限并让他们看到不同的页面。
这是我到目前为止在互联网上找到的,但它不起作用,因为它说:ApplicationUser could not be found
private void CreateRoles(IServiceProvider serviceProvider)
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
Task<IdentityResult> roleResult;
string email = "someone@somewhere.com";
//Check that there is an Administrator role and create if not
Task<bool> hasAdminRole = roleManager.RoleExistsAsync("Administrator");
hasAdminRole.Wait();
if (!hasAdminRole.Result)
{
roleResult = roleManager.CreateAsync(new IdentityRole("Administrator"));
roleResult.Wait();
}
//Check if the admin user exists and create it if not
//Add to the Administrator role
Task<ApplicationUser> testUser = userManager.FindByEmailAsync(email);
testUser.Wait();
if (testUser.Result == null)
{
ApplicationUser administrator = new ApplicationUser();
administrator.Email = email;
administrator.UserName = email;
Task<IdentityResult> newUser = userManager.CreateAsync(administrator, "_AStrongP@ssword!");
newUser.Wait();
if (newUser.Result.Succeeded)
{
Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(administrator, "Administrator");
newUserRole.Wait();
}
}
}
非常感谢为我的应用设置管理员的任何帮助。
【问题讨论】:
-
@blfuentes 以及如何为用户分配角色..?
-
无法找到ApplicationUser;你什么时候收到这个错误?编译前还是运行时?
-
@Amir 在我构建应用程序之前
标签: c# asp.net asp.net-core asp.net-identity asp.net-core-2.2