我们可以让 ActionFilter extends Enum<T> asp core2

Could we have ActionFilter extends Enum<T> asp core2

我是 Asp Core 的新手,我试图实现一个扩展枚举类型

IActionFilter
public class IndexFilter<T> : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
          // for example T.GetType.GetProperties
    }
}

并在控制器中

public class CategoryController : Controller
{
    [Route("")]
    [HttpGet]
    [ServiceFilter( typeof( IndexFilter<Category> ))]
    public async Task<IActionResult> Index()
    { 
          //  Code
    }
    ....
}

我尝试了一下,但偶然发现了一个异常

An unhandled exception has occurred while executing the request.
System.InvalidOperationException: No service for type 'AuthWebApi.Filters.IndexFilter`1[AuthWebApi.Models.Entities.Category]' has been registered.
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)

我尝试将 Startup.cs 更改为:

services.AddScoped<IndexFilter<CategoryParent>>();
services.AddScoped<IndexFilter<Object>>();
services.AddScoped<IndexFilter<>>();

没有任何效果,除非我设置 IndexFilter 以匹配控制器:

services.AddScoped<IndexFilter<Category>>();

这使得 Enumerable class 表现得像一个普通的 class。

您可以使用如下通用类型注册 IndexFilter<T>

services.AddScoped(typeof(IndexFilter<>));

那么,就可以解析服务了:

[ServiceFilter(typeof(IndexFilter<Category>))]
public async Task<IActionResult> Category()
{
    return Ok();
}
[ServiceFilter(typeof(IndexFilter<CategoryParent>))]
public async Task<IActionResult> CategoryParent()
{
    return Ok();
}