我有一个 Controller 基类,在其中我有创建、删除和 getbyid 方法。 请看代码
public abstract class BaseControllerWithAuthorization<TEntity, TCreateRequest, TResponse, TManager, TKey> : Controller
where TEntity : BaseModel<TKey>
where TManager : IBusinessManager<TEntity, TCreateRequest, TKey>
{
protected readonly TManager Manager;
protected readonly ILocalizationService LocalizationService;
protected readonly ILogger<Controller> Logger;
protected readonly IMapper Mapper;
protected BaseControllerWithAuthorization(TManager manager, ILocalizationService localizationService, ILogger<Controller> logger, IMapper mapper)
{
Manager = manager;
LocalizationService = localizationService;
Logger = logger;
Mapper = mapper;
}
[Route("create")]
[HttpPost]
[Permission(nameof(TEntity), Crud.Create)]
public async Task<IActionResult> Create([FromBody] TCreateRequest request)
{
var result = await Manager.CreateAsync(request);
return Ok(new ApiResponse(LocalizationService, Logger).Ok(Mapper.Map<TEntity, TResponse>(result)));
}
[Route("delete/{id}")]
[HttpDelete]
[Permission(nameof(TEntity), Crud.Delete)]
public async Task<IActionResult> Delete(TKey id)
{
await Manager.DeleteAsync(id);
return Ok(new ApiResponse(LocalizationService, Logger).Ok(true));
}
[Route("get/id/{id}")]
[HttpGet]
[Permission(nameof(TEntity), Crud.Select)]
public async Task<IActionResult> GetById(TKey id)
{
var result = await Manager.GetByIdAsync(id);
return Ok(new ApiResponse(LocalizationService, Logger).Ok(Mapper.Map<TEntity, TResponse>(result)));
}
}
我必须将 TEntity 类名传递给 PermissionAttribute 以执行一些授权操作,但不幸的是 nameof(TEntity) 代码无法正常工作,并给我“TEntity”字符串定义而不是“Customer”(例如)
如果没有办法传递类名字符串,也许你可以告诉我另一种方法来进行授权过程。为此,我还发送了我的 PermissionAttribute 类代码
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
public string Entity { get; set; }
public Crud? Crud { get; set; }
public PermissionAttribute(string entity, Crud crud) : base("Permission")
{
Entity = entity;
Crud = crud;
}
}
感谢您的帮助。
最佳答案
不可能评估 nameof
以获得实际类型,因为 nameof
是在编译时确定的。它成为一个 string
,无论 T
最终是什么。
由于不能用当前实例注入(inject)属性,所以您进入了死胡同。你可能想改变你的方法。也许消息过滤器可以帮助您解决这个问题。
关于c# - 属性中的通用类型类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49940962/