Asp.Net 核心 Web 应用程序:使用 IExceptionFilter 与自定义中间件的全局异常处理

Asp.Net Core Web app: Global exception handling using IExceptionFilter vs custom middleware

Asp.Net Core 支持两种方式为 Web 应用程序进行全局异常处理,实现 IExceptionFilter 或通过创建自定义中间件。一个比另一个有什么优势吗?我看到的大多数参考资料都是关于创建自定义中间件的。

ASP.NET核心docs解释了这两种方法之间的主要区别。它声明异常过滤器:

  • Handle unhandled exceptions that occur in Razor Page or controller creation, model binding, action filters, or action methods.
  • Do not catch exceptions that occur in resource filters, result filters, or MVC result execution.

甚至还有关于何时使用中间件以及何时使用异常过滤器的建议:

Exception filters:

  • Are good for trapping exceptions that occur within actions.
  • Are not as flexible as error handling middleware.

Prefer middleware for exception handling. Use exception filters only where error handling differs based on which action method is called. For example, an app might have action methods for both API endpoints and for views/HTML. The API endpoints could return error information as JSON, while the view-based actions could return an error page as HTML.