能否让ActionFilter扩展Enum <t> asp core2

时间:2018-12-31 22:48:15

标签: asp.net-core .net-core action-filter custom-action-filter asp.net-core-mvc-2.1

我是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设置为与Controller匹配:

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

这使得Enumerable类的行为类似于普通类。

1 个答案:

答案 0 :(得分:0)

您可以使用以下通用类型注册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();
}
相关问题