使用ASP.net Identity和Web API获取用户角色

时间:2016-06-29 23:10:24

标签: c# asp.net asp.net-web-api asp.net-identity asp.net-roles

我目前正在尝试获取给定用户的角色列表,并且在将其应用到我们正在使用它的上下文中时遇到了一些麻烦。我能够通过此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 };
    }

}

但似乎无法弄清楚我需要投入到这个中以获得用户的角色列表。我们使用现有数据库方法实现了Entity Frameworks Code First,并从这些表中提取。奇怪的是,虽然没有AspNetUserRoles表,因为我猜它只是关联两个表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课程,

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

我觉得应该有一个简单的修复,但我不能完全理解它是什么。

1 个答案:

答案 0 :(得分:1)

刚刚找到问题的答案。我缺少的主要是使用用户管理器,这使事情变得如此简单。然后我只需要把东西放到我已定义的函数中。这是代码。

[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 };
    }
}