Asp.Net Core 5多项目架构下UserManager<ApplicationUser>未注册报错求助
问题根因
IdentityHostingStartup类是程序集级别的启动配置,仅对当前所属项目生效,你将Identity服务注册放在API项目的该类中,两个管理员Web应用作为独立运行的项目,不会加载API项目的启动配置- 你手动删除了超级管理员项目自身的Identity服务注册,导致该项目的依赖注入容器中不存在
UserManager<ApplicationUser>、SignInManager<ApplicationUser>等Identity核心服务,页面调用时就会抛出未注册的报错
修复方案
快速适配方案(兼容现有复用仓储层的需求)
- 第一步:在仓储类库中新增共享的Identity服务注册扩展方法,避免多项目重复写配置,新增
IdentityServiceExtensions.cs文件代码如下:
using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using ABC_App.Repository.Models; // 替换为你实际的ApplicationUser对应命名空间 namespace ABC_App.Repository { public static class IdentityServiceExtensions { public static IServiceCollection AddSharedIdentity(this IServiceCollection services, string connectionString) { // 注册共享上下文 services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(connectionString)); // 注册Identity核心服务,所有项目复用该配置 services.AddIdentity<ApplicationUser, IdentityRole>() .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationContext>() .AddDefaultTokenProviders() .AddDefaultUI(); return services; } } }
- 第二步:替换API项目的原有配置,修改
IdentityHostingStartup.cs如下:
public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { services.AddSharedIdentity(context.Configuration.GetConnectionString("DefaultConnection")); }); }
- 第三步:恢复两个管理员项目的Identity配置,在各自项目的
Startup.cs的ConfigureServices方法中调用扩展方法,同时要在两个管理员项目的appsettings.json中添加和API项目完全一致的DefaultConnection数据库连接字符串:
public void ConfigureServices(IServiceCollection services) { // 原有其他服务注册逻辑保留 services.AddSharedIdentity(Configuration.GetConnectionString("DefaultConnection")); // 原有其他服务注册逻辑保留 }
注意:请全局搜索解决方案中所有
ApplicationUser的引用,确保所有地方引用的都是仓储类库中定义的ABC_App.Repository.Models.ApplicationUser,没有本地脚手架生成的同名不同命名空间的类,否则会出现类型不匹配导致的服务注册无效问题。
- 第四步:清理解决方案,重新生成所有项目后运行即可解决报错。
推荐长期架构调整方案
如果要长期维护该项目,建议调整为标准的前后端分离认证架构:
- API项目作为资源服务器,仅保留JWT令牌校验逻辑,移除
AddDefaultUI()这类UI相关配置 - 两个管理员客户端作为OAuth2客户端,所有身份认证、用户操作都通过调用API接口完成,客户端本地不直接访问数据库,也不注册Identity核心服务
- 该架构可避免多项目重复配置Identity,也更符合分布式系统的安全规范。
内容的提问来源于stack exchange,提问作者Noor
相关产品推荐
相关产品推荐

