Search code examples
asp.net-web-apiidentityrolesuser-roles

Get all Identity roles in ASP .Net Core WebAPI


I have a task to fetch all identity roles in my database. i use below code to fetch all roles. in Asp .Net core 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;
        }

   }

But i got following Error

 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?)

plese give me a solution to solve this error

when i change it to

 Task<List<IdentityRole>> AllUserRoles()
 {
     return  _roleManager.Roles;
 }

I got error like

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?)

Solution

  • I think that the problem is the return type you are using there. From your code, I assume that _roleManager.Roles is of type System.Linq.IQueryable<Microsoft.AspNetCore.Identity.IdentityRole>.

    Your return type is instead Task<List<IdentityRole>> or Task<IList<string>>

    You can change the return type of your function to IQueryable as this:

        public List<IdentityRole> AllUserRoles()
        {
           return _roleManager.Roles.ToList();
        }
           
    

    or do something like:

        public Task<List<IdentityRole>> AllUserRoles()
        {
            return Task.FromResult(_roleManager.Roles.ToList());
        }