ASP.NET Core Identity不会注入UserManager

我有一个较旧的asp.net核心身份数据库,我想将一个新项目(一个web api)映射到它。

仅仅为了测试,我复制了Models文件夹,以及上一个项目中的ApplicationUser文件(ApplicationUser只是inheritance自IdentityUser,无论如何都没有变化) – 首先做数据库似乎是一个坏主意。

我在ConfigureServices中注册了Identity(但是我没有将它添加到管道中,因为我的唯一目的是使用UserStore)

services.AddIdentity() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); 

我的期望是现在

  UserManager 

……应该自动注入构造函数中。

但是,将以下代码添加到控制器私有UserManager _userManager时;

  public UserController(UserManager userManager) { _userManager = userManager; } 

…每次调用api都会以exception结束:HttpRequestException:响应状态代码不表示成功:500(内部服务器错误)。

删除“注入”代码可以顺利运行可以接受请求的web api。

在我的任何代码到达之前发生这种情况很难调试。 知道为什么会这样吗?

PS从“exception设置”窗口启用所有exception后,我得到了这个:

抛出exception:’System.InvalidOperationException’
Microsoft.Extensions.DependencyInjection.dll

附加信息:尝试激活’Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4 [Namespace.Models]时,无法解析类型’Namespace.Data.ApplicationDbContext’的服务。 ApplicationUser,Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole,Namespace.Data.ApplicationDbContext,System.String]”。

你有app.UseIdentity();Configure方法中调用:

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { /*...*/ app.UseIdentity(); /*...*/ } 

编辑你是否在services.AddIdentity()之前有这一行.AddIdentity services.AddIdentity()行?

  public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); } 

这应该工作正常。 另请检查ApplicationDbContextinheritance自IdentityDbContext

DI容器无法解析依赖项。 将其添加到服务集合中

 services.AddTransient>(); services.AddTransient(); 

您还应该熟悉官方文档

 public void ConfigureServices(IServiceCollection services){ ... var identityBuilder = services.AddIdentityCore(user => { // configure identity options user.Password.RequireDigit = true; user.Password.RequireLowercase = false; user.Password.RequireUppercase = false; user.Password.RequireNonAlphanumeric = false; user.Password.RequiredLength = 6; }); identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(IdentityRole), identityBuilder.Services); identityBuilder.AddEntityFrameworkStores().AddDefaultTokenProviders(); ... }