I have an ASP.NET Core 3.1 Web API project and I'm using the v3.1.10 packages for aspnetcore.tools, SQL Server, jwtbearer, and I have installed the v2.2.0 of Microsoft.AspNetCore.Identity.
I'm getting this error message at postman output line:
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[API.Authentication.ApplicationUser]' while attempting to activate 'API.Controllers.AuthenticationController'.
My startup file is :
services.AddControllers();
services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
services.AddIdentity<ApplicationUser,IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = Configuration["JWT:ValidAudience"],
ValidIssuer = Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
};
});
and my controller is :
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationUser> _roleManager;
private readonly IConfiguration _configuration;
public AuthenticationController(UserManager<ApplicationUser> userManager, RoleManager<ApplicationUser> roleManager,IConfiguration configuration)
{
_userManager = userManager;
_roleManager = roleManager;
_configuration = configuration;
}
[HttpPost]
[Route("Register")]
public async Task<IActionResult> Register([FromBody] RegisterModel model)
{
var userExist = await _userManager.FindByNameAsync(model.UserName);
if (userExist !=null)
{
return StatusCode(StatusCodes.Status500InternalServerError, new Response {Status="Error",Massage="User Already Exist" });
}
ApplicationUser user = new ApplicationUser()
{
Email = model.Email,
SecurityStamp = Guid.NewGuid().ToString(),
UserName = model.UserName
};
var result = await _userManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Massage = "User creation failed" });
}
return Ok(new Response { Status="Success" , Massage = "Successfuly created"});
}
i couldn't find the what's wrong with this code.