【发布时间】:2023-04-06 06:56:01
【问题描述】:
我有一个使用 Identity 的 ASP.NET Core 应用程序。它可以工作,但是当我尝试向数据库添加自定义角色时,我遇到了问题。
在 Startup ConfigureServices 我已将身份和角色管理器添加为这样的范围服务:
services.AddIdentity<Entities.DB.User, IdentityRole<int>>()
.AddEntityFrameworkStores<MyDBContext, int>();
services.AddScoped<RoleManager<IdentityRole>>();
在 Startup 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:我在创建项目时使用“无身份验证”从头开始学习身份。
【问题讨论】:
-
我建议使用个人用户帐户创建另一个项目,以便您可以比较使用包含身份的模板时为您设置的内容
-
添加了“个人用户帐户”的全新项目不包含任何设置角色的代码。
-
不,它没有,但它可能有一些代码连接你没有正确连接的依赖项
-
在不相关的说明中,您应该避免在
Configure方法中注入像RoleManager这样的作用域依赖项,因为它会阻止底层DbContext被正确处理。相反,请考虑使用IServiceScopeFactory.CreateScope()创建一个服务范围,该范围将在您的SeedRoles方法返回时释放(您可以查看github.com/openiddict/openiddict-samples/blob/master/samples/… 的示例)
标签: asp.net asp.net-core asp.net-core-mvc asp.net-identity-3