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

.NET Core 6自定义身份存储报错:未注册UserManager服务

问题分析与解决

错误提示No service for type 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered的核心问题出在:**你代码里有地方注入了UserManager,但实际注册的是针对自定义ApplicationUser的UserManager`服务**,类型不匹配自然找不到对应服务。

给你整理了具体的排查和修复步骤:

1. 检查所有注入UserManager的代码

  • 翻遍你的控制器、服务类等所有用到UserManager的地方,确保注入的是UserManager<ApplicationUser>,不是默认的UserManager<IdentityUser>。
    举个例子,控制器里应该这么写:
    private readonly UserManager<ApplicationUser> _userManager;
    
    public AccountController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    

2. 确认自定义Store的实现与注册没问题

  • 先确保CustomUserStore确实实现了IUserStore<ApplicationUser>(或者你自己定义的ICustomUserStore),别写错类型。
  • 再检查AddIdentity的注册代码,泛型参数必须是你的自定义用户和角色,Store的泛型也别搞错:
    builder.Services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddUserStore<CustomUserStore>()
        .AddRoleStore<CustomRoleStore>()
        .AddDefaultTokenProviders(); // 建议加上,不然密码重置这类功能会用不了
    
    另外,如果你的ICustomUserStore是继承自IUserStore<ApplicationUser>的自定义接口,得额外注册接口和实现类的映射:
    builder.Services.AddScoped<ICustomUserStore, CustomUserStore>();
    builder.Services.AddScoped<ICustomRoleStore, CustomRoleStore>();
    

3. 检查身份认证中间件的配置

  • 确保Program.cs里用的是对应自定义用户类型的认证中间件,别强制指定默认的IdentityUser。
  • 如果手动配置了AddAuthentication,要保证默认方案和自定义身份的方案一致:
    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
        options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    })
    .AddCookie(IdentityConstants.ApplicationScheme, options =>
    {
        // 你的Cookie配置
    });
    

4. 确认ApplicationUser和ApplicationRole的定义没错

  • 要保证ApplicationUser继承自IdentityUser(或者你自定义的基础用户类),ApplicationRole继承自IdentityRole,类型参数别写错:
    public class ApplicationUser : IdentityUser
    {
        // 你的自定义属性
    }
    
    public class ApplicationRole : IdentityRole
    {
        // 你的自定义属性
    }
    

5. 清理缓存重新生成项目

有时候编译缓存会搞出类型匹配的异常,删掉项目的bin和obj目录,重新生成解决方案再试试。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:15:40