c# - 属性中的通用类型类名

标签 c# generics attributes

我有一个 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/

相关文章:

c# - RoutePrefix 不工作 Asp.NET MVC

Magento : Display html element based on product attribute set?

c# - 使用 51degrees.mobi 进行平板电脑与手机检测

c# - 测试 FluentValidation ChildRules

java - ArrayList<anyClassObject> 的动态初始化

java - List<List<?>> 和 List<List> 是 java 中不兼容的类型

c# - DirectoryEntry.Invoke ChangePassword 上的 Active Directory 访问被拒绝异常

java - 解码 IBM/360 列二进制格式的十六进制数

java - 是否可以有一个泛型类,其中类型是未知维度的数组?

javascript - 如何设置JavaScript对象的属性值?