asp.netasp.net-mvcexceptioncustom-attributesasp.net-mvc-custom-filter

How to catch an Exception thrown by a custom IAuthorizationFilter in my custom ExceptionFilterAttribute


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
{
}

Solution

  • According to Microsoft documentation here Authorization filter

    • Run first
    • Determine whether the user is authorized for the request
    • Short-circuit the pipeline if the request is not authorized

    And here

    • The exception will not be handled
    • Exception filters will not handle the exception

    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