使用自定义IdentityUser类注册Identity时遇InvalidOperationException异常
问题解决:AddEntityFrameworkStores 角色类型异常
错误原因
你混淆了两个完全不同的Identity实体类型:
IdentityRole(或其派生类)是角色本身的实体,对应数据库中的角色表(如AspNetRoles)IdentityUserRole是用户与角色的关联实体,对应关联表(如AspNetUserRoles)
AddIdentity<ApplicationUser, TRole>的第二个泛型参数TRole要求必须是继承自IdentityRole<TKey>的角色实体,但你传入了IdentityUserRole,这直接触发了异常。你自定义的ApplicationUserRole是关联实体而非角色实体,所以替换它无法解决问题。
解决方案
情况1:使用默认角色体系,无需自定义角色
直接将AddIdentity的第二个泛型参数改为默认的IdentityRole,修正后代码如下:
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } }
情况2:需要自定义角色+自定义用户角色关联表
如果要扩展角色实体(给角色加额外字段),同时扩展用户角色关联表,按以下步骤操作:
- 创建继承自
IdentityRole的自定义角色类 - 创建继承自
IdentityUserRole<string>(指定主键类型)的自定义用户角色关联类 - 在
AddIdentity中传入自定义角色类,再通过AddUserRole注册自定义关联类 - 在
ApplicationDbContext中配置这些自定义实体
示例代码:
// 自定义角色类 public class ApplicationRole : IdentityRole { // 角色额外字段 public string Description { get; set; } } // 自定义用户角色关联类 public class ApplicationUserRole : IdentityUserRole<string> { // 关联表额外字段 public string MyRole { get; set; } } // 注册Identity服务 builder.Services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.SignIn.RequireConfirmedAccount = true) .AddUserRole<ApplicationUserRole>() // 注册自定义用户角色关联类 .AddEntityFrameworkStores<ApplicationDbContext>(); // ApplicationDbContext配置 public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } }
内容的提问来源于stack exchange,提问作者unelectricpostrequest
相关产品推荐
相关产品推荐

