获取 ASP .Net Core WebAPI 中的所有身份角色
Posted
技术标签:
【中文标题】获取 ASP .Net Core WebAPI 中的所有身份角色【英文标题】:Get all Identity roles in ASP .Net Core WebAPI 【发布时间】:2021-10-10 02:54:22 【问题描述】:我的任务是获取数据库中的所有身份角色。我使用下面的代码来获取所有角色。在 Asp .Net 核心 WebAPI 中
UserRoleService.cs
public class UserRoleService
private readonly RoleManager<IdentityRole> _roleManager;
public UserRoleService(RoleManager<IdentityRole> roleManager)
_roleManager=roleManager;
public Task<IList<string>> AllUserRoles()
return _roleManager.Roles;
但我得到以下错误
Cannot implicitly convert type
'System.Linq.IQueryable<Microsoft.AspNetCore.Identity.IdentityRole>' to
'System.Threading.Tasks.Task<System.Collections.Generic.List<string>>'.
An explicit conversion exists (are you missing a cast?)
请给我一个解决这个错误的方法
当我把它改成
Task<List<IdentityRole>> AllUserRoles()
return _roleManager.Roles;
我遇到了类似的错误
Cannot implicitly convert type
'System.Linq.IQueryable<Microsoft.AspNetCore.Identity.IdentityRole>' to
'System.Threading.Tasks.Task<System.Collections.Generic.List<Microsoft.AspNetCore.Identity.IdentityRole>>'.
An explicit conversion exists (are you missing a cast?)
【问题讨论】:
【参考方案1】:我认为问题在于您在那里使用的返回类型。
根据您的代码,我假设 _roleManager.Roles 的类型为 System.Linq.IQueryable<Microsoft.AspNetCore.Identity.IdentityRole>
。
您的返回类型改为Task<List<IdentityRole>>
或Task<IList<string>>
您可以将函数的返回类型更改为 IQueryable,如下所示:
public List<IdentityRole> AllUserRoles()
return _roleManager.Roles.ToList();
或者做类似的事情:
public Task<List<IdentityRole>> AllUserRoles()
return Task.FromResult(_roleManager.Roles.ToList());
【讨论】:
以上是关于获取 ASP .Net Core WebAPI 中的所有身份角色的主要内容,如果未能解决你的问题,请参考以下文章