【问题标题】:Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager` while attempting to activate 'AuthenticateController'尝试激活“AuthenticateController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务
【发布时间】: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"]))
         };
     });
}

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-core asp.net-web-api


    【解决方案1】:

    您没有为 UserApplication 配置依赖注入。有不同的方法可以做到这一点,例如

    services.AddDefaultIdentity<UserApplication>(options =>
       options.SignIn.RequireConfirmedAccount = true)
       .AddEntityFrameworkStores<ApplicationDbContext>();
    

    或者,如果您想要更精细的控制,

    services.AddIdentityCore<AppUser>(opt => {
        opt.Password.RequiredLength = 8;
        ...
    })
    .AddSignInManager()
    .AddRoles<IdentityRole>();
    

    【讨论】:

    • 嗨,谢谢它现在可以工作了:))
    • 如果此答案解决了您的问题,您可能需要将其标记为这样
    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2019-05-20
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多