asp.net-core - Asp.Net Core Web应用程序: Global exception handling using IExceptionFilter vs custom middleware

标签 asp.net-core asp.net-core-mvc asp.net-core-webapi

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/

相关文章:

c# - 尝试从 Asp.net core 中的 Azure Key Vault 访问对象值

c# - 手动添加参数?

azure - Application Insights 未显示所有错误

c# - 使用 Blazor Asp.Net Core 托管模板时获取 "NETSDK1045 The current .NET SDK does not support .NET Core 3.0 as a target"

c# - 依赖注入(inject) .NET Core - InvalidOperationException

Angular 7. NullInjectorError : No provider for HttpClient! 即使 app.module 有 HttpClientModule。如何解决?

c# - 在模型 .net 核心 web api 中返回具有 null 必需属性的 BadRequest

c# - Web API .net core 2请求检查请求的 header 不为空

c# - 多个发布类型 asp.net 5 MVC 6 API

ASP.NET Core MVC 健康检查失败