gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:21:23 25 4
gpt4 key购买 nike

我目前正在尝试获取给定用户的角色列表,但在将其与我们使用它的上下文相匹配时遇到了一些问题。我之前能够使用此 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 Framework 代码优先,并从这些表中提取。奇怪的是,虽然没有 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; }
}

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

最佳答案

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

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

关于c# - 使用 ASP.net Identity 和 Web API 获取用户角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com