对于
_userManager.GetRolesAsync(user)
,它叫
userRoleStore.GetRolesAsync
public virtual async Task<IList<string>> GetRolesAsync(TUser user)
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return await userRoleStore.GetRolesAsync(user, CancellationToken);
}
userRoleStore.GetRolesAsync
UserStore
.
-
public class CustomUserStore : UserStore<IdentityUser>
{
public CustomUserStore(DbContext context, IdentityErrorDescriber describer = null) : base(context, describer)
{
}
public override async Task<IList<string>> GetRolesAsync(IdentityUser user, CancellationToken cancellationToken = default(CancellationToken))
{
var roleNames = await base.GetRolesAsync(user, cancellationToken);
var roleIds = await Context.Set<IdentityRole>()
.Where(r => roleNames.Contains(r.Name))
.Select(r => r.Id)
.ToListAsync();
return roleIds;
}
}
-
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddUserStore<CustomUserStore>()
.AddEntityFrameworkStores<ApplicationDbContext>()
;
services.AddScoped<DbContext, ApplicationDbContext>();
-
然后,您将通过获取角色id集合
var user = await _userManager.FindByNameAsync(User.Identity.Name);
var roles = await _userManager.GetRolesAsync(user);