0

我是 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 类的行为就像一个普通类。

4

1 回答 1

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();
}
于 2019-01-01T06:58:01.080 回答