属性中的通用类型类名称

时间:2018-04-20 11:47:24

标签: c# generics attributes

我有一个基本控制器类,在这里我有创建,删除和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;
    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

由于nameof是在编译时确定的,因此无法评估nameof以获取实际类型。无论string最终是什么,它都会成为T

由于无法使用当前实例注入属性,因此您将陷入死胡同。您可能想要改变您的方法。也许邮件过滤器可以帮助你。