简体   繁体   中英

Unable to list data from Role-based HttpGet request using ASP.NET Core identity

I have created HttpGet following ASP.NET Core identity but I'm having problem to get data based on role. In my program I have three roles user, manager, admin. And in GET method only login user should be able to list data where admin can list all the company data but user and manager can see/list only those company data where they are associate.

Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Web.Data;
using Web.Features.Roles;
using Web.Features.Company;
using Web.Features.Shared;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Web.Controllers
{
    [ApiController]
    [Route("api/company")]
    public class CompanyController : ControllerBase
    {
        private readonly DataContext dataContext;

        public CompanyController(DataContext dataContext)
        {
            this.dataContext = dataContext;
        }

        private static Expression<Func<Company, CompanyDto>> MapToDto()
        {
            return x => new CompanyDto
            {
                Name = x.Name,
                Active = x.Active,
                CompanyPopulation = x.CompanyPopulation,
                Id = x.Id
            };
        }

        [HttpGet]
        [Authorize]
        public IEnumerable<CompanyDto> GetAll()
        {
            var result = dataContext
               .Set<Company>()
               .Select(MapToDto()).ToList();
            if (User.IsInRole("admin"))  //I tried to check using IsInRole method but it doesn't work
            {
                return result;
            }

            return null;
        }
    }
}

CompanyDto

public class CompanyDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
    public int CompanyPopulation { get; set; }
}

I tried to check using IsInRole method but it doesn't work

Firstly, you can try to get list of role names of current user using following code snippet, and check if you assigned role(s) to current user.

var user = await _userManager.GetUserAsync(User);
var roles = await _userManager.GetRolesAsync(user);

If you do not assign user with specified role, please refer to the following code snippet to add the specified user to the named role.

var user = await _userManager.GetUserAsync(User);

await _userManager.AddToRoleAsync(user, "role_name_here");

Test Result

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM