也许我错过了一些东西,但是我阅读了一堆关于使用 .NET Core 2.0 进行身份验证和授权的文档和文章,但我没有找到任何关于用户管理的内容。
我想要实现的是拥有一个管理员用户界面,可以创建用户、列出所有现有用户并将他们分配给预定义的角色和/或预定义的策略。
我尝试这样做没有成功(我在尝试使用诸如 IEnumerable<IdentityUser>
之类的模型时遇到了关于无效构造函数的问题:
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.
我无法获得
RoleManager
在任何 Controller 中。它适用于 UserManager,但不能适用于 RoleManager。我添加了 services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
到启动,所以我教它会自动注入(inject)DI...
ApplicationUser
定义如下:namespace KaraokeServices.Data
{
public class ApplicationUser : IdentityUser
{
}
}
我定义了一个用户 Controller ,例如:
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);
}
}
}
这是 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>
但我总是被错误困住......
我做错了什么?
最佳答案
代替
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
将管理员添加到
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<AuthContext>()
.AddUserManager<UserManager>()
.AddSignInManager<SignInManager>()
.AddDefaultTokenProviders();
并尝试
@model ICollection<ApplicationUser>
反而?
关于asp.net - 使用 ASP.NET Core 2.0 进行用户管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47352601/