Asp.Net Core Web应用程序:使用IExceptionFilter与自定义中间件进行全局异常处理 [英] Asp.Net Core Web app: Global exception handling using IExceptionFilter vs custom middleware

查看:381
本文介绍了Asp.Net Core Web应用程序:使用IExceptionFilter与自定义中间件进行全局异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Asp.Net Core supports two ways to do global exception handling for a Web Application, implementing IExceptionFilter or by creating custom middleware. Is there any advantage of one over the other? Most references I see are for creating custom middleware.

推荐答案

ASP.NET Core

The ASP.NET Core docs explains the main differences between these two approaches. It states that exception filters:

  • 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.

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

There's even advice for when to use middleware and when to use exception filters:

异常过滤器:

  • 非常适合捕获动作中发生的异常.
  • 不像错误处理中间件那样灵活.

首选中间件进行异常处理.仅在根据调用哪种操作方法进行错误处理不同的地方使用异常过滤器.例如,一个应用程序可能同时具有API端点和视图/HTML的操作方法. API端点可以将错误信息作为JSON返回,而基于视图的操作可以将错误页面作为HTML返回.

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 Web应用程序:使用IExceptionFilter与自定义中间件进行全局异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆