简体   繁体   English

ASP.Net Core如何获得EF Core和Identity中的用户角色

[英]ASP.Net Core how to get the user role in EF Core and Identity

Hi I'm building a API using Identity with a custom user class,and EF Core. 嗨,我正在使用带有自定义用户类和EF Core的Identity构建API。 I want to get the name of the role that belongs to an user. 我想获取属于用户的角色的名称。 The diagram of the tables is the following(ignore userclaims and userlogins): 这些表的图表如下(忽略用户声明和用户登录): 在此处输入图片说明

As you can see the Roles and Users is N to N so internally Identity made a junction table named UserRoles, my contoller looks like this: 如您所见,角色和用户是N到N,因此Identity在内部创建了一个名为UserRoles的联结表,我的控制器如下所示:

Route ("api/[controller]")]
    public class UserController : Controller {
        private readonly DBContext _db;
        private readonly UserManager<Usuario> _userManager;
        public UserController (DBContext db, UserManager<Usuario> userManager) {
            this._db = db;
        }
        [HttpGet ("GetUserById/{id}", Name = "GetUserById")]
        public async Task<IActionResult> GetUserById (string id) {
            try {

                var user = await this._db.Users.Where (x => x.Id == id).Include (x => x.Roles).FirstOrDefaultAsync ();
                if (user == null) {
                    return NotFound ();
                }
                return Ok (user);
            } catch (Exception e) {
                Console.WriteLine (e.Message);
                return BadRequest ();
            }
        }

When I called it in Postman I get the following response: 当我在Postman中调用它时,得到以下响应:

在此处输入图片说明

As you can see in the roles part all I get is: 正如您在角色部分中看到的,我得到的是:

"roles": [
        {
            "userId": "d88b0c2d-25c5-4da9-ad05-45f69dec67ff",
            "roleId": "a83a60ca-f011-43ce-be3d-8b71403aa86e"
        }
    ]

That data belongs to the junction table not the Role table itself, I dont want that. 该数据属于联结表而不是角色表本身,我不希望那样。

What I really want is the "real" Role table data, Any idea how can I achieve that? 我真正想要的是“真实的”角色表数据,我知道该如何实现?

In sql it would be something like : 在SQL中将是这样的:

select *
    from AspNetUsers as a,AspNetUserRoles as b,AspNetRoles as c 
    where a.Id = b.UserId and b.RoleId= c.Id 
var user = await _userManager.FindByIdAsync(UserId);
var roles = await _userManager.GetRolesAsync(user);

return OK(new { User = user, Roles = roles });

This produces role names, either way the only way to get this back to your api call is to return a ViewModel or other option as Chris points out it isn't possible to directly call.. Its so round about to achieve something so small. 这会产生角色名称,这两种方法都会使它返回到您的api调用,唯一的方法是返回ViewModel或其他选项,因为Chris指出无法直接调用。

At any rate this is a second option to get the "Role" names without having to touch your db context. 无论如何,这是获得“角色”名称的第二种选择,而无需触摸您的数据库上下文。

If you want the Id's pull that from RoleManager<IdentityRole> or tap your dbcontext. 如果您希望Id'sRoleManager<IdentityRole>提取该Id's ,或点击您的dbcontext。

Callings it Roles in what ever you do might cause interference since roles[] will already exist in the return of the User . 在您执行的任何操作中将其称为Roles可能会引起干扰,因为Roles roles[]User的返回中已经存在。

Unfortunately, there's not navigation properties on UserRole , so it's a manual affair. 不幸的是, UserRole上没有导航属性,因此是手动操作。 You'd need to do something like: 您需要执行以下操作:

var userRoleIds = user.Roles.Select(r => r.RoleId);
var roles = db.Roles.Where(r => userRoleIds.Contains(r.Id));

Then, you can map those on to the user via a view model. 然后,您可以通过视图模型将这些映射到用户。 For example: 例如:

public class UserViewModel
{
    ...
    public List<string> Roles { get; set; }
}

Then: 然后:

var model = new UserViewModel
{
    ...
    Roles = roles.Select(r => r.Name).ToList()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM