自定义IdentityUser(WebApp1User)后调用时出现“未注册Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]服务”的异常
嗨,我看了你的问题,这个报错其实很典型——说白了就是你已经把默认的Identity用户换成自定义的WebApp1User了,但项目里还有地方在揪着原来的IdentityUser不放,导致依赖注入容器找不到对应的服务。下面我给你一步步理清楚问题和解决办法:
核心问题分析
你注释掉了原来的AddDefaultIdentity<IdentityUser>,换成了AddDefaultIdentity<WebApp1User>,这一步是对的,但问题出在两个地方:
- 你同时配置了
ApplicationDbContext和WebApp1Context两个数据库上下文,自定义用户和Identity服务的绑定关系混乱了; - 项目里的身份相关页面(比如默认的登录、个人资料页,或者布局页里的登录状态组件)还在尝试注入
UserManager<IdentityUser>,但你现在注册的服务是UserManager<WebApp1User>,DI容器找不到前者自然就报错了。
具体解决步骤
1. 统一Identity的数据库上下文,别搞“双线操作”
默认情况下,ASP.NET Core Identity会用ApplicationDbContext来存储用户数据,你新建的WebApp1Context完全没必要和Identity绑定,反而会搞混关系。建议调整成如下配置:
var builder = WebApplication.CreateBuilder(args); // 1. 配置主数据库上下文(用于Identity和业务数据) var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); // 2. 移除WebApp1Context的Identity关联(如果它是业务上下文,单独用就行,别碰Identity) // 注释掉这部分: // var connectionString2 = builder.Configuration.GetConnectionString("WebApp1ContextConnection"); // builder.Services.AddDbContext<WebApp1Context>(options => options.UseSqlServer(connectionString2)); // 3. 注册自定义IdentityUser,绑定到ApplicationDbContext builder.Services.AddDefaultIdentity<WebApp1User>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); // 剩下的配置不变 builder.Services.AddRazorPages(); var app = builder.Build(); // ... 后面的中间件配置保持原样
2. 让所有身份页面都用自定义用户类型
如果你用的是Visual Studio默认生成的身份验证页面(登录、注册、个人资料这些),它们可能还在引用IdentityUser。这时候你需要重新生成身份页面,指定用WebApp1User:
- 右键项目 → 添加 → 新搭建的基架项
- 选择「身份」→ 添加
- 勾选你需要的身份页面(比如登录、管理),然后在「数据上下文类」选
ApplicationDbContext,「用户类」选WebApp1User
如果是你自己写的自定义页面,一定要检查后台模型的注入代码,比如:
// 正确的注入方式(用WebApp1User) private readonly UserManager<WebApp1User> _userManager; private readonly SignInManager<WebApp1User> _signInManager; public ProfileModel(UserManager<WebApp1User> userManager, SignInManager<WebApp1User> signInManager) { _userManager = userManager; _signInManager = signInManager; }
绝对不能再用UserManager<IdentityUser>了!
3. 更新数据库结构,同步自定义用户字段
调整完配置后,需要执行数据库迁移,把WebApp1User的自定义字段(Name、DOB)同步到数据库:
打开Visual Studio的「包管理器控制台」,依次执行:
Add-Migration AddCustomUserProperties Update-Database
4. 检查布局页的身份组件
从报错堆栈看,异常是在布局页的PartialTagHelper里触发的,大概率是_Layout.cshtml里引用的_LoginPartial.cshtml还在使用旧的用户类型。你需要打开_LoginPartial.cshtml.cs(如果有后台代码),确保注入的是SignInManager<WebApp1User>,而不是SignInManager<IdentityUser>。
最后再确认一遍
整个项目的身份验证体系要完全统一用WebApp1User:从DI注册的服务,到页面模型的注入,再到数据库上下文的绑定,别让任何地方再出现IdentityUser,这样依赖注入容器就能正确找到对应的服务,报错自然就消失了。
内容来源于stack exchange

