asp.net-core.net-coreaction-filtercustom-action-filterasp.net-core-mvc-2.1

Could we have ActionFilter extends Enum<T> asp core2


I am new to Asp Core, and I tried to implement an IActionFilter that extends an Enum Type

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

And in the controller

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

I gave it a shot and I stumbled over an Exception

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)

I tried to change Startup.cs to :

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

and nothing worked, unless I set IndexFilter to match the Controller:

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

Which makes the Enumerable class acts like a normal class.


Solution

  • You could register IndexFilter<T> with generic type like below:

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

    Then, it will be able to resolve the service:

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