Asp.Net Core支持两种方法来实现Web应用程序的全局异常处理,方法是实现IExceptionFilter或通过创建自定义中间件。一个相对于另一个有什么优势吗?我看到的大多数引用文献都是关于创建自定义中间件的。
最佳答案
ASP.NET Core 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.
关于asp.net-core - Asp.Net Core Web应用程序: Global exception handling using IExceptionFilter vs custom middleware,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47981785/