获取具有 ASP.net 身份和 Web API 的用户角色

Get User Roles with ASP.net Identity and Web API

我目前正在尝试获取给定用户的角色列表,但在将其与我们使用它的上下文相匹配时遇到了一些问题。我能够通过此获取所有可用角色的列表API功能更早,

[HttpGet]
[Route("GetRoles")]
public async Task<ApiResponse<List<RoleViewModel>>> GetRoles()
{
    try
    {
        //Get Roles
        var roles = await (from r in _db.AspNetRoles
                     select new RoleViewModel { Id = r.Id, Name = r.Name}).ToListAsync();
        return new ApiResponse<List<RoleViewModel>>{ Success = true, Result =  roles };

    }
    catch(Exception ex)
    {
        return new ApiResponse<List<RoleViewModel>> { Success = false, Message = ex.Message };
    }

}

但似乎无法弄清楚我需要将什么投入到这个中才能获得用户角色列表。我们从现有数据库方法中使用实体框架代码优先,并从那些 table 中提取。奇怪的是,虽然没有 AspNetUserRoles table,因为我猜它只是关联了两个 tables AspNetUsers 和 AspNetRoles。无论如何,这是有问题的功能,

[HttpGet]
[Route("GetUserRoles")]
public async Task<ApiResponse<List<RoleViewModel>>> GetUserRoles(string userName)
{
    try
    {
        var userRoles = await (_db.AspNetUsers.FirstOrDefault(u => u.UserName == userName).AspNetRoles).ToListAsync();
    }
    catch (Exception ex)
    {
        return new ApiResponse<List<RoleViewModel>> { Success = false, Message = ex.Message };
    }
}

我得到的当前错误是 AspNetRole 不包含 ToListAsync() 的定义。我认为异步的东西让我有点不舒服。最后是RoleViewModel供参考,

public class RoleViewModel
{
    public string Id { get; set; }

    [Required]
    [StringLength(256)]
    public string Name { get; set; }
}

和 ApiResponse class,

public class ApiResponse<TResult>
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public TResult Result { get; set; }
}

我觉得应该有一个简单的修复方法,但我不太明白它是什么。

刚刚找到了我的问题的答案。我缺少的主要是用户管理器的使用,这让事情变得容易多了。然后我只需要将东西放入我已经定义的函数中。这是代码。

[HttpGet]
[Route("GetUserRoles")]
public async Task<ApiResponse<List<RoleViewModel>>> GetUserRoles(string userName)
{
    try
    {
        // Get the user in question
        var aspUser = (from u in _db.AspNetUsers
                       where u.UserName == userName
                       select u).FirstOrDefaultAsync();

        // Check if the user was found
        if (aspUser == null)
        {
            throw new Exception("User was not found");
        }

        // Get the roles associated with that user
        var userRoles = await UserManager.GetRolesAsync(aspUser.Result.Id.ToString());

        // Setup a RoleViewModel list of roles and iterate through userRoles adding them to the list
        List<RoleViewModel> roleList = new List<RoleViewModel>();
        foreach (var u in userRoles)
        {
            var item = new RoleViewModel { Name = u };
            roleList.Add(item);
        }

        return new ApiResponse<List<RoleViewModel>> { Success = true, Result = roleList };
    }
    catch (Exception ex)
    {
        return new ApiResponse<List<RoleViewModel>> { Success = false, Message = ex.Message };
    }
}