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

激活AdminUserSetController时无法解析UserManager<ApplicationUser>服务

问题解决方法

你的错误根源是Identity服务注册与自定义用户类不匹配,具体修复步骤如下:

  • 修复Identity服务注册
    在Program.cs中,你注册Identity时使用的是默认的IdentityUser,但控制器依赖的是自定义的ApplicationUser,需要修改AddIdentity的泛型参数:

    // 原代码
    builder.Services
        .AddIdentity<IdentityUser, IdentityRole>()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    
    // 修改为
    builder.Services
        .AddIdentity<ApplicationUser, IdentityRole>()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    
  • 修复DbContext继承关系
    你的ApplicationDbContext继承的是无泛型的IdentityDbContext,它默认使用IdentityUser,需要改为继承IdentityDbContext<ApplicationUser>,这样EF Core才会使用你的自定义用户类:

    // 原代码
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :base(options)
        {
    
        }
    
        public DbSet<ApplicationUser> ApplicationUsers { get; set; }
        public DbSet<Company> Companies { get; set; }
    }
    
    // 修改为
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :base(options)
        {
    
        }
    
        public DbSet<Company> Companies { get; set; }
    }
    

    注意:不需要再显式声明DbSet<ApplicationUser>,因为IdentityDbContext<ApplicationUser>已经包含了对应的用户集合。

  • 验证依赖注入
    修改后,UserManager<ApplicationUser>就能被正确注入到AdminUserSetController中,Index方法也能正常执行并获取用户列表。

完成以上修改后,重新编译运行即可解决该错误。

内容的提问来源于stack exchange,提问作者Huy Hoang Nguyen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:55:19