我使用的是带有标识和JWT的Asp net core 3.0。我可以毫无问题地获得所有用户,但角色总是为空或什么都没有。
[Route("ListUsers")]
[AllowAnonymous]
public IActionResult ListUsers()
{
var users = userManager.Users;
return Ok(users);
}
您可以循环所有用户,并通过以下方式获取每个用户的角色:
foreach (var user in _userManager.Users.ToList())
{
var roles = await _userManager.GetRolesAsync(user);
}
另一种解决方案是在用户和角色之间创建多对多关系,这样您就可以使用EF查询include
来获取角色。基于此解决方案,以下代码示例在asp.net核心3.0中使用身份:
应用程序用户:
foreach (var user in _userManager.Users.ToList())
{
var roles = await _userManager.GetRolesAsync(user);
}
应用程序角色:
public class ApplicationRole : IdentityRole
{
public ICollection<ApplicationUserRole> UserRoles { get; set; }
}
ApplicationUserRole:
public class ApplicationUserRole : IdentityUserRole<string>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
}
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();
});
}
}
启动:
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
并获取用户和角色(UserManager<ApplicationUser>
(:
var Users = _userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();
不要忘记在_LoginPartial.cshtml
中更改为UserManager<ApplicationUser>/SignInManager<ApplicationUser>
。