I have a custom ExceptionFilterAttribute
on my api controllers to handle exceptions, as well as a custom IAuthorizationFilter
on the same controllers to handle custom security.
The ExceptionFilterAttribute
catches exceptions and works fine for the most part, however it does not catch exceptions thrown from my IAuthorizationFilter
. Those exceptions just get dumped back to the user raw without ever hitting the exception attribute.
Is there a way to do this? I attempted having both implement IOrderedFilter
and specifying that the ExceptionFilterAttribute be processed first, but that didn't appear to change anything.
(this is .NET 6 fwiw)
This is the source of the controller all my controllers inherit:
[ExceptionHandling(Order = 1)] // inherits ExceptionFilterAttribute
[EntityAuthorizationFilter(Order = 2)] // implements IAuthorizationFilter
public class ApiController : ControllerBase
{
}
According to Microsoft documentation here Authorization filter
And here
IAuthorizationFilter
is executed before any other filter for every MVC request. So if it throws an exception or it's not authorized it will short-circuit the pipeline.What you can try is to use exception handler middleware rather than an exception filter as described here