You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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>服务,通常由以下原因导致:

  1. 未正确配置Identity服务与数据库上下文的关联
  2. 数据库上下文未继承Identity专用的上下文类
  3. 认证授权中间件顺序错误或缺少Razor Pages路由映射

内容的提问来源于stack exchange,提问作者Ayaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:01:07