当在ASP.NET Core Identity中自定义IdentityRole并在UserManager上使用时,可能会引发异常。下面是一个解决方法,包含了代码示例:
ApplicationRole继承自IdentityRole:public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base()
{
}
public ApplicationRole(string roleName) : base(roleName)
{
}
}
Startup.cs文件的ConfigureServices方法中配置Identity服务并指定自定义的ApplicationRole:services.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
ApplicationDbContext.cs文件中更新ApplicationDbContext类,将IdentityRole替换为ApplicationRole:public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
}
UserManager的地方,注入UserManager并指定自定义的ApplicationRole:private readonly UserManager _userManager;
private readonly RoleManager _roleManager;
public YourController(UserManager userManager,
RoleManager roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
现在,您应该能够在ASP.NET Core Identity中自定义IdentityRole并在UserManager上使用,而不会引发异常。