.NET Core MVC 7 Identity服务解析错误:无法激活RegisterModel求助
.NET Core MVC 7 Identity 服务解析错误
错误信息
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'LearnIdentity.Areas.Identity.Pages.Account.RegisterModel'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
解决方案
以下是针对该错误的排查和修复步骤:
检查Identity服务注册:在
Program.cs中确认已添加Identity服务配置,示例代码如下:// 添加Identity服务,使用默认IdentityUser并关联DbContext builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>();验证DbContext继承关系:确保你的数据库上下文类继承自
IdentityDbContext<IdentityUser>,示例:public class ApplicationDbContext : IdentityDbContext<IdentityUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } }确认DbContext服务注册:在
Program.cs中添加DbContext的依赖注入配置,关联你的数据库连接字符串:builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));检查中间件顺序:确保认证和授权中间件的顺序正确,且添加了Razor Pages路由映射:
app.UseRouting(); // 必须在UseAuthorization之前添加UseAuthentication app.UseAuthentication(); app.UseAuthorization(); // MVC路由 app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); // 映射Identity的Razor Pages app.MapRazorPages();
错误原因说明
该错误是因为依赖注入容器中未注册UserManager<IdentityUser>服务,通常由以下原因导致:
- 未正确配置Identity服务与数据库上下文的关联
- 数据库上下文未继承Identity专用的上下文类
- 认证授权中间件顺序错误或缺少Razor Pages路由映射
内容的提问来源于stack exchange,提问作者Ayaz
相关产品推荐
相关产品推荐

