当在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
上使用,而不会引发异常。