我是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类的行为类似于普通类。
答案 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();
}