我有一个使用Identity的ASP.NET Core应用程序。它可以工作,但是当我尝试将自定义角色添加到数据库时,我遇到了问题。
在Startup ConfigureServices
中,我添加了Identity和角色管理器作为这样的作用域服务:
services.AddIdentity<Entities.DB.User, IdentityRole<int>>()
.AddEntityFrameworkStores<MyDBContext, int>();
services.AddScoped<RoleManager<IdentityRole>>();
并在启动Configure
中注入RoleManager并将其传递给我的自定义类RolesData
:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
RoleManager<IdentityRole> roleManager
)
{
app.UseIdentity();
RolesData.SeedRoles(roleManager).Wait();
app.UseMvc();
这是RolesData
类:
public static class RolesData
{
private static readonly string[] roles = new[] {
"role1",
"role2",
"role3"
};
public static async Task SeedRoles(RoleManager<IdentityRole> roleManager)
{
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
var create = await roleManager.CreateAsync(new IdentityRole(role));
if (!create.Succeeded)
{
throw new Exception("Failed to create role");
}
}
}
}
}
应用程序构建没有错误,但在尝试访问它时,我收到以下错误:
尝试激活'Microsoft.AspNetCore.Identity.RoleManager
时无法解析类型'Microsoft.AspNetCore.Identity.IRoleStore`1 [Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole]'的服务
我做错了什么?我的直觉说我将RoleManager添加为服务有什么问题。
PS:在创建项目以从头学习身份时,我使用了“无身份验证”。
答案 0 :(得分:15)
我做错了什么?我的直觉说我将RoleManager添加为服务的方式有问题。
注册部分实际上很好,您应该删除services.AddScoped<RoleManager<IdentityRole>>()
,因为services.AddIdentity()
已经为您添加了角色管理器。
您的问题很可能是由通用类型不匹配引起的:当您使用services.AddIdentity()
致电IdentityRole<int>
时,您尝试使用RoleManager
解决IdentityRole
,这是一个等价物IdentityRole<string>
(string
是ASP.NET核心标识中的默认密钥类型)。
更新您的Configure
方法以获取RoleManager<IdentityRole<int>>
参数,它应该有效。
答案 1 :(得分:2)
我遇到了这个问题
'Microsoft.AspNetCore.Identity.RoleManager'类型没有服务
此页面是Google上的第一个结果。它没有回答我的问题,所以我想我将解决方案放在这里,以供其他可能遇到此问题的人使用。
ASP.NET Core 2.2
我缺少的行是Startup.cs文件中的 .AddRoles()。
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
希望这对某人有帮助
来源:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-2.2(在底部)
答案 2 :(得分:0)
这是我的解决方案的种子,它是用户和角色ASP.NET Core 2.2
Startup.cs
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole<Guid>>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
...
...
SeedData.Initialize(app.ApplicationServices);
)
SeedData.cs
public static void Initialize(IServiceProvider serviceProvider)
{
using (var scope = serviceProvider.CreateScope())
{
var provider = scope.ServiceProvider;
var context = provider.GetRequiredService<ApplicationDbContext>();
var userManager = provider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = provider.GetRequiredService<RoleManager<IdentityRole<Guid>>>();
// automigration
context.Database.Migrate();
InstallUsers(userManager, roleManager);
}
}
private static void InstallUsers(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole<Guid>> roleManager)
{
const string USERNAME = "admin@mysite.com";
const string PASSWORD = "123456ABCD";
const string ROLENAME = "Admin";
var roleExist = roleManager.RoleExistsAsync(ROLENAME).Result;
if (!roleExist)
{
//create the roles and seed them to the database
roleManager.CreateAsync(new IdentityRole<Guid>(ROLENAME)).GetAwaiter().GetResult();
}
var user = userManager.FindByNameAsync(USERNAME).Result;
if (user == null)
{
var serviceUser = new ApplicationUser
{
UserName = USERNAME,
Email = USERNAME
};
var createPowerUser = userManager.CreateAsync(serviceUser, PASSWORD).Result;
if (createPowerUser.Succeeded)
{
var confirmationToken = userManager.GenerateEmailConfirmationTokenAsync(serviceUser).Result;
var result = userManager.ConfirmEmailAsync(serviceUser, confirmationToken).Result;
//here we tie the new user to the role
userManager.AddToRoleAsync(serviceUser, ROLENAME).GetAwaiter().GetResult();
}
}
}