我正在尝试在ASP.NET Identity中配置基于角色的授权。我想这样做,以便管理员用户可以看到用户及其角色的列表(在索引页面上)并更改各个用户的角色(在编辑页面上)。
这是我的背景:
modelBuilder.Entity<IdentityUser>()
.HasKey<string>(k => k.Id)
.ToTable("Users");
modelBuilder.Entity<IdentityUserRole>()
.HasKey(r => new { r.RoleId, r.UserId })
.ToTable("UserRoles");
modelBuilder.Entity<IdentityUserLogin>()
.HasKey<string>(f => f.UserId)
.ToTable("UserLogins");
modelBuilder.Entity<IdentityRole>()
.ToTable("Roles");
我在UsersController.cs中的索引操作:
public ActionResult Index()
{
return View(db.Users.Include(i => i.Roles).ToList());
}
索引视图:
@model List<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>
//stuff
@foreach (var item in Model)
{
<tr class="index-item" data-href="@Url.Action("Details", "Users", new { id=item.Id })">
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.Roles)">
</td>
<td class="index-links">
//stuff
</td>
</tr>
}
</table>
我的角色表:
我的UserRoles表:
基于这些表,用户具有“查看者”角色。但是,视图不显示角色名称,而是显示角色ID:
如何让它显示角色名称(在本例中为“Viewer”)?
答案 0 :(得分:4)
IdentityUserRole
类没有IdentityUser
和IdentityRole
的导航属性,只有UserId
和RoleId
,它不容易获得用户的角色。所以我们需要使用2 db调用
var users = db.Users.Include(u => u.Roles);
var roles = db.Roles.Include(r => r.Users);
像这样的ViewModel
public class UsersRolesViewModel
{
public List<ApplicationUser> Users { set; get; }
public List<IdentityRole> Roles { set; get; }
}
和视图
@foreach (var user in Model.Users)
{
<tr class="index-item" data-href="@Url.Action("Details", "Users", new { id= user.Id })">
<td>
@user.Email
</td>
<td>
@string.Join(",", roles.Where(r => r.Users.Any(u => u.UserId == user.Id)).Select(r => r.Name))
</td>
<td class="index-links">
//stuff
</td>
</tr>
}
修改强>
您可以通过一个查询获得所需的所有数据
var users = (from u in db.Users
let query = (from ur in db.Set<IdentityUserRole>()
where ur.UserId.Equals(u.Id)
join r in db.Roles on ur.RoleId equals r.Id select r.Name)
select new UserDto() {User = u, Roles = query.ToList<string>()})
.ToList();
使用这个简单的模型
public class UserDto
{
public ApplicationUser User { set; get; }
public List<string> Roles { set; get; }
}
和视图
@foreach (var user in Model.Users)
{
var appUser = user.ApplicationUser;
var roles = user.Roles;
<tr class="index-item" data-href="@Url.Action("Details", "Users", new { id= appUser.Id })">
<td>
@appUser.Email
</td>
<td>
@string.Join(",", roles)
</td>
<td class="index-links">
//stuff
</td>
</tr>
}
答案 1 :(得分:0)
using System.Linq;
using System.Data;
using System.Data.Entity;
var db = new ApplicationDbContext();
var Users = db.Users.Include(u => u.Roles);
foreach (var item in Users)
{
string UserName = item.UserName;
string Roles = string.Join(",", item.Roles.Select(r=>r.RoleId).ToList());
}