Maybe I miss something but, I read a bunch of documentation and articles regarding authentication and authorization using .NET Core 2.0, but I didn't find anything regarding user management.
What I'm trying to achieve is to have an Administrator user interface that can create Users, list all existing users and assign them to predefined role(s) and/or predefined policies.
I tried without success to do so without any luck (I get problems when trying to use a model such as IEnumerable<IdentityUser>
regarding an invalid constructor :
InvalidOperationException: A suitable constructor for type 'System.Collections.Generic.IEnumerable`1[Microsoft.AspNetCore.Identity.IdentityUser]' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
and I'm unable to get the RoleManager
in any Controller. It works fine with the UserManager, but never with the RoleManager. I added
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
to the startup, so I taught it will be DI injected automagically...
ApplicationUser
is defined as follows:
namespace KaraokeServices.Data
{
public class ApplicationUser : IdentityUser
{
}
}
I Defined a UserController such as :
namespace KaraokeServices.Controllers
{
[Route("[controller]/[action]")]
public class UserController : Controller
{
private readonly UserManager<ApplicationUser> userManager;
public UserController(ApplicationDbContext pContext, SignInManager<ApplicationUser> pSignInManager, ILogger<AccountController> logger)
{
userManager = pSignInManager.UserManager;
}
[HttpGet]
public IActionResult Index()
{
List<ApplicationUser> users = new List<ApplicationUser>();
users = userManager.Users.ToList();
return View(users);
}
}
}
And here is the User/Index.cshtml
@page
@model IEnumerable<ApplicationUser>
@{
ViewData["Title"] = "Gestion des utilisateurs";
}
<h2>@ViewData["Title"]</h2>
<form method="post">
<table class="table">
<thead>
<tr>
<th>Courriel</th>
<th>Roles</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<td>@user.Email</td>
<td></td>
<td>
<a asp-page="./Edit" asp-route-id="@user.Id">Éditer</a>
<button type="submit" asp-page-handler="delete" asp-route-id="@user.Id">
Effacer
</button>
</td>
</tr>
}
</tbody>
</table>
<a asp-page="./Create">Créer</a>
</form>
but I'm always stucked with the error ...
What do I do wrong?
Instead of
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
Add the managers in
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<AuthContext>()
.AddUserManager<UserManager>()
.AddSignInManager<SignInManager>()
.AddDefaultTokenProviders();
And try with
@model ICollection<ApplicationUser>
instead?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With