【发布时间】:2018-05-01 08:17:53
【问题描述】:
也许我错过了一些东西,但是我阅读了一堆关于使用 .NET Core 2.0 进行身份验证和授权的文档和文章,但我没有找到任何关于用户管理的内容。
我想要实现的是拥有一个管理员用户界面,可以创建用户、列出所有现有用户并将他们分配给预定义的角色和/或预定义的策略。
我尝试这样做没有成功(我在尝试使用 IEnumerable<IdentityUser> 等模型时遇到了关于无效构造函数的问题:
InvalidOperationException:适用于“System.Collections.Generic.IEnumerable`1[Microsoft.AspNetCore.Identity.IdentityUser]”类型的构造函数 无法定位。确保类型是具体的并且服务是 为公共构造函数的所有参数注册。
我无法在任何控制器中获取RoleManager。它适用于 UserManager,但不能适用于 RoleManager。我加了
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
到启动,所以我教它会自动注入 DI...
ApplicationUser定义如下:
namespace KaraokeServices.Data
{
public class ApplicationUser : IdentityUser
{
}
}
我定义了一个 UserController 比如:
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>
但我总是被错误困住......
我做错了什么?
【问题讨论】:
-
请添加
ApplicationUser的定义。 -
我刚刚编辑了帖子以添加特定信息。 ApplicationUser 以及 UserController。
-
你需要添加包括
AddUserStore()和AddRoleStore()见Issues with injecting RoleManager
标签: asp.net .net-core asp.net-authorization