ASP.NET Core 2.1 显示用户和角色
Posted
技术标签:
【中文标题】ASP.NET Core 2.1 显示用户和角色【英文标题】:ASP.NET Core 2.1 displaying users and roles 【发布时间】:2019-07-10 19:46:24 【问题描述】:为了显示用户及其在核心 2.1 中的角色,我遵循了示例 *** 。我没有错误,但我没有显示用户角色。我认为这可能是我的观点,由于某种原因,我的代码返回了一个电子邮件地址而不是用户角色。
ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser,
ApplicationRole, string, IdentityUserClaim<string>,
ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
protected override void OnModelCreating(ModelBuilder builder)
base.OnModelCreating(builder);
builder.Entity<ApplicationUserRole>(userRole =>
userRole.HasKey(ur => new ur.UserId, ur.RoleId );
userRole.HasOne(ur => ur.Role)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
userRole.HasOne(ur => ur.User)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
);
public DbSet<ApplicationUser> ApplicationUser get; set;
Startup.cs
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
应用程序用户
public class ApplicationUser : IdentityUser
public ICollection<ApplicationUserRole> UserRoles get; set;
public class ApplicationUserRole : IdentityUserRole<string>
public virtual ApplicationUser User get; set;
public virtual ApplicationRole Role get; set;
public class ApplicationRole : IdentityRole
public ICollection<ApplicationUserRole> UserRoles get; set;
索引方法:
public async Task<IActionResult> Index(int? page )
var users = from u in _userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role) select u;
return View(users.ToPagedList(pageNumber, pageSize));
查看
@html.DisplayFor(m => item.UserRoles)
【问题讨论】:
【参考方案1】:您将所有内容都放在ApplicatonUser
类中。首先重新排列您的模型类,如下所示:
public class ApplicationUser : IdentityUser
public ICollection<ApplicationUserRole> UserRoles get; set;
public class ApplicationUserRole : IdentityUserRole<string>
public virtual ApplicationUser User get; set;
public virtual ApplicationRole Role get; set;
public class ApplicationRole : IdentityRole
public ICollection<ApplicationUserRole> UserRoles get; set;
现在UserRoles
是一个集合,你不能用@Html.DisplayFor(m => item.UserRoles)
显示它,而是你必须按如下方式遍历这个集合:
@model List<ApplicationUser>
@
foreach (ApplicationUser applicationUser in Model)
<div>UserName : @applicationUser.UserName</div>
<br/>
<h4>User's Role</h4>
<hr/>
foreach (ApplicationUserRole applicationUserRole in applicationUser.UserRoles)
<div>RoleName: @applicationUserRole.Role.Name</div>
【讨论】:
我没有意识到我的类在我的 ApplicationUser 类中,我现在可以通过视图看到它。谢谢,它只是很少的资源在 asp 2.1 中的角色以上是关于ASP.NET Core 2.1 显示用户和角色的主要内容,如果未能解决你的问题,请参考以下文章
ASP.Net Core 如何在 EF Core 和 Identity 中获取用户角色