I'm getting this error in Login Controller.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[UsersAuth.IdentityAuth.UserApplication]' while attempting to activate 'UsersAuth.Controllers.AuthenticateController'.
here is Authenticate Controller constructor:
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;
}
and here is ConfigureServices in startup.cs:
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"]))
};
});
}
CodePudding user response:
You didn't configure Dependency Injection for UserApplication
. There are different ways to do that, for example
services.AddDefaultIdentity<UserApplication>(options =>
options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
or, if you want more granular control,
services.AddIdentityCore<AppUser>(opt => {
opt.Password.RequiredLength = 8;
...
})
.AddSignInManager()
.AddRoles<IdentityRole>();
CodePudding user response:
I would comment but I don't have rep yet to do it so here it goes: Is UserManager class your creation? I don't see a call registering it in IServiceCollection to be resolved when constructing your controller.
An example registration for you UserManager could look like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<UserManager<UserApplication>>();
// other registrations follow
}