ASP.NET Core Identity脚手架无法选择自定义ApplicationUser类的问题求助
问题描述
在ASP.NET Core应用中搭建Identity登录、注册页面时,选择页面与DbContext类后,自定义用户类ApplicationUser对应的选择框处于禁用状态,无法选择。相关代码定义如下:
DbContext定义
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
自定义用户与角色类
public class ApplicationUser : IdentityUser
public class ApplicationRole : IdentityRole
上下文已引用ApplicationUser与ApplicationRole类,尝试回滚Microsoft.AspNetCore.Identity.UI包版本后问题仍存在。手动将Register.cshtml.cs与Login.cshtml.cs中的IdentityUser替换为ApplicationUser后未生效,还出现以下错误:
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'MyApp.Web.Areas.Identity.Pages.Account.RegisterModel'.
原因分析
- 选择框禁用的核心原因:Visual Studio的Identity脚手架会自动检测项目中Identity服务的配置状态。如果
Program.cs(或Startup.cs)未正确注册基于ApplicationUser的Identity服务,脚手架无法识别自定义用户类的合法性,因此禁用选择框。 - 手动替换后报错的原因:仅修改页面模型的用户类型,但DI容器中注册的仍是基于
IdentityUser的UserManager服务,页面模型依赖的UserManager<ApplicationUser>未被注册,导致依赖注入失败。
解决方案
步骤1:正确配置Identity服务
在Program.cs(.NET 6+)或Startup.cs(.NET 5及更早)中,注册Identity时明确指定自定义的ApplicationUser和ApplicationRole:
// .NET 6+ Program.cs示例 builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<ApplicationRole>() .AddEntityFrameworkStores<ApplicationDbContext>();
若需精细配置密码、锁定规则等,可使用AddIdentity:
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>(options => { // 示例:配置密码规则 options.Password.RequireDigit = true; options.Password.RequiredLength = 6; }) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders() .AddDefaultUI();
步骤2:重新运行Identity脚手架
完成服务注册后,重新启动Identity脚手架:
- 右键项目→添加→新搭建的项目→Identity
- 此时
ApplicationUser选择框会变为可选中状态,勾选需要生成的页面(登录、注册等)后生成,脚手架会自动生成基于ApplicationUser的页面模型与视图,无需手动替换类型。
步骤3:修复已手动修改的文件(可选)
如果已手动修改过页面模型文件,建议删除后重新通过脚手架生成;若需保留修改,需确保页面模型的依赖注入参数匹配自定义用户类型:
// RegisterModel构造函数需注入UserManager<ApplicationUser> public RegisterModel( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<RegisterModel> logger, IEmailSender emailSender) { _userManager = userManager; _signInManager = signInManager; _logger = logger; _emailSender = emailSender; }
步骤4:更新数据库迁移(可选)
首次配置自定义用户类时,需同步更新数据库结构:
Add-Migration AddCustomIdentityUser Update-Database
内容的提问来源于stack exchange,提问作者Alex Parvanov

