[英]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.我已经按照 ASP.NET Core 标识创建了 HttpGet,但是我在根据角色获取数据时遇到了问题。 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.在 GET 方法中,只有登录用户才能列出数据,管理员可以列出所有公司数据,但用户和经理只能查看/列出他们关联的公司数据。
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我尝试使用 IsInRole 方法进行检查,但它不起作用
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测试结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.