Reputation: 87
I want to create Roles and assign users to those Roles, I have created Roles but I didn't know how to assign users to them, I tried to add UserManager to services in startup but it doesn't work. I have this error:
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[PFE_Management.Models.AppUser]' while attempting to activate 'PFE_Management.Controllers.RoleController'.
This the controller:
namespace PFE_Management.Controllers
{
public class RoleController : Controller
{
private RoleManager<IdentityRole> roleManager;
private UserManager<AppUser> userManager;
public RoleController(RoleManager<IdentityRole> roleMgr, UserManager<AppUser> userMrg)
{
roleManager = roleMgr;
userManager = userMrg;
}
//some code here
// le code qui suive c'est ajouter ou supprimer un utilisateur pour un Role
public async Task<IActionResult> Update(string id)
{
//some code here
}
[HttpPost]
public async Task<IActionResult> Update(RoleModification model)
{
IdentityResult result;
if (ModelState.IsValid)
{
foreach (string userId in model.AddIds ?? new string[] { })
{
AppUser user = await userManager.FindByIdAsync(userId);
if (user != null)
{
result = await userManager.AddToRoleAsync(user, model.RoleName);
if (!result.Succeeded)
Errors(result);
}
}
foreach (string userId in model.DeleteIds ?? new string[] { })
{
AppUser user = await userManager.FindByIdAsync(userId);
if (user != null)
{
result = await userManager.RemoveFromRoleAsync(user, model.RoleName);
if (!result.Succeeded)
Errors(result);
}
}
}
if (ModelState.IsValid)
return RedirectToAction(nameof(Index));
else
return await Update(model.RoleId);
}
}
}
This is services in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
Upvotes: 0
Views: 1706
Reputation: 119146
AddDefaultIdentity
doesn't add the user manager into the service collection. You need to add it yourself. For example:
services.AddDefaultIdentity<IdentityUser>(...)
.AddRoles<IdentityRole>()
.AddUserManager<IdentityUser>() // <-- add this
.AddEntityFrameworkStores<ApplicationDbContext>();
Upvotes: 2