ASP.NET Core MVC中注入UserManager失败的问题咨询
问题原因及解决方法
核心问题
你没在Program.cs里注册ASP.NET Core Identity的核心服务,依赖注入(DI)容器找不到UserManager<IdentityUser>的注册信息,自然没法注入到LoginController里。只加DbContext不够,必须显式配置Identity相关服务。
解决步骤
1. 给Program.cs补加Identity服务注册
在添加DbContext的代码后面,加上Identity服务的注册代码:
var connectionString = builder.Configuration.GetConnectionString("AppDb"); builder.Services.AddDbContext<ApplicationDbContext>(x => x.UseSqlServer(connectionString)); // 新增:注册Identity核心服务 builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false) .AddEntityFrameworkStores<ApplicationDbContext>();
如果你需要用到自定义角色(比如你继承了IdentityRole),可以改用AddIdentity:
builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = false) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders();
2. 删除ApplicationDbContext里多余的OnConfiguring方法
你已经在Program.cs里配置了数据库连接字符串,OnConfiguring里的重复配置完全没必要,还可能导致冲突,直接删掉:
public class ApplicationDbContext : IdentityDbContext<IdentityUser, IdentityRole, string> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } // 删掉这个方法 // protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) // { // ... // } }
3. 修正LoginController里的异步调用(推荐)
FindByEmailAsync是异步方法,你现在的调用没加await,拿到的只是一个任务对象,不是实际的用户数据,改成这样更合理:
public async Task<IActionResult> Index() { var user = await _userManager.FindByEmailAsync("user@home.se"); return View(user); // 按你的实际需求返回视图或数据 }
验证
改完以上内容后重启应用,DI容器就能正常解析UserManager<IdentityUser>并注入到LoginController里,之前的错误就会消失。
内容的提问来源于stack exchange,提问作者MTplus
相关产品推荐
相关产品推荐

