首页 > 解决方案 > userManager.GetRolesAsync(user) 扩展 IdentityRole 后返回空列表

问题描述

我需要向 IdentityRole 添加一个 List 属性以建立多对多关系。完成此操作并运行代码优先迁移后,一切似乎都很好。但是,现在当我尝试为用户提取角色时,即使我可以看到它们存在于数据库中,结果也始终为空。知道为什么会发生这种情况吗?

public class Role : IdentityRole
{
    public Role(string name) : base(name) { }
    public List<FeatureRole> FeatureRoles { get; set; }
}
public class FeatureRole
{
    public int FeatureId { get; set; }
    public Feature Feature { get; set; }
    public string RoleId { get; set; }
    public Role Role { get; set; }
}
public class Feature
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }
    public Permission AvailablePermissions { get; set; }
    public Permission Permissions { get; set; }
    public bool IsSystem { get; set; }
    public List<FeatureRole> FeatureRoles { get; set; }
}
public async Task<CurrentUserJS> AuthenticateAsync(string username, string password)
{
    try
    {
        var user = await _userManager.FindByNameAsync(username);
        if(user != null)
        {
            var signInResult = await _signInManager.PasswordSignInAsync(user, password, false, false);
            if(signInResult.Succeeded)
            {
                var roles = await _userManager.GetRolesAsync(user); // <-- roles = [] always

                //....

}

标签: c#asp.net-coreasp.net-identityusermanager

解决方案


推荐阅读