尝试激活“AuthenticateController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务
Posted
技术标签:
【中文标题】尝试激活“AuthenticateController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务【英文标题】:Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager` while attempting to activate 'AuthenticateController' 【发布时间】:2022-01-04 01:59:47 【问题描述】:我在登录控制器中收到此错误。
System.InvalidOperationException:尝试激活“UsersAuth.Controllers.AuthenticateController”时,无法解析“Microsoft.AspNetCore.Identity.UserManager`1[UsersAuth.IdentityAuth.UserApplication]”类型的服务。
这里是 Authenticate Controller 构造函数:
public class AuthenticateController : ControllerBase
private readonly UserManager<UserApplication> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IConfiguration _configuration;
public AuthenticateController(UserManager<UserApplication> userManager, RoleManager<IdentityRole> roleManager, IConfiguration configuration)
_userManager = userManager;
_roleManager = roleManager;
_configuration = configuration;
这里是 startup.cs 中的 ConfigureServices:
public void ConfigureServices(IServiceCollection services)
services.AddControllers();
services.AddDbContext<ApplicationDbContext>(options=>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddAuthentication(options =>
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
)
.AddJwtBearer(options =>
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = Configuration["JWT:ValidIssuer"],
ValidAudience = Configuration["JWT:ValidAudience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:SecretKey"]))
;
);
【问题讨论】:
【参考方案1】:您没有为 UserApplication
配置依赖注入。有不同的方法可以做到这一点,例如
services.AddDefaultIdentity<UserApplication>(options =>
options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
或者,如果您想要更精细的控制,
services.AddIdentityCore<AppUser>(opt =>
opt.Password.RequiredLength = 8;
...
)
.AddSignInManager()
.AddRoles<IdentityRole>();
【讨论】:
嗨,谢谢它现在可以工作了:)) 如果此答案解决了您的问题,您可能需要将其标记为这样以上是关于尝试激活“AuthenticateController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务的主要内容,如果未能解决你的问题,请参考以下文章
尝试激活 RedGate Multiscript 时“无法显示此页面”