Search code examples
c#asp.net-coreaction-filter

Order of global filters in ASP.NET Core


I have two global exception filters in Startup

config.Filters.AddService(typeof(ExceptionFilter));

and

config.Filters.AddService(typeof(JsonExceptionFilter));

I was always under impression that if the same filter is added first it is executed first.

But when I've added ExceptionFilter first it is executed second.

UPDATE 1

ConfigureServices method:

services
    .AddMvc(
         config =>
         {
            config.Filters.AddService(typeof(ExceptionFilter));
            config.Filters.AddService(typeof(JsonExceptionFilter));
         });

Solution

  • With MVC, you can specify an order value that determines the order of execution for your filters. I don't know if the same applies to ASP.NET Core, and I don't have an IDE in front of me to check. Would you mind trying this?

    config.Filters.AddService(typeof(ExceptionFilter), 2);
    config.Filters.AddService(typeof(JsonExceptionFilter), 1);
    

    Even if that isn't it, check to see if there is another overload of AddService that does accept a parameter to specify the order.