[英]Unable to list data from Role-based HttpGet request using ASP.NET Core identity
我已经按照 ASP.NET Core 标识创建了 HttpGet,但是我在根据角色获取数据时遇到了问题。 在我的程序中,我有三个角色用户、经理、管理员。 在 GET 方法中,只有登录用户才能列出数据,管理员可以列出所有公司数据,但用户和经理只能查看/列出他们关联的公司数据。
这是我的代码:
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;
}
}
}
公司名称
public class CompanyDto
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
public int CompanyPopulation { get; set; }
}
我尝试使用 IsInRole 方法进行检查,但它不起作用
首先,您可以尝试使用以下代码片段获取当前用户的角色名称列表,并检查您是否为当前用户分配了角色。
var user = await _userManager.GetUserAsync(User);
var roles = await _userManager.GetRolesAsync(user);
如果您没有为用户分配指定角色,请参考以下代码片段将指定用户添加到命名角色中。
var user = await _userManager.GetUserAsync(User);
await _userManager.AddToRoleAsync(user, "role_name_here");
测试结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.