gpt4 book ai didi

exception-handling - 如何在 ASP.NET Core 中正确实现 ExceptionFilterAttribute

转载 作者:行者123 更新时间:2023-12-04 13:47:36 26 4
gpt4 key购买 nike

是否有任何关于如何正确实现 ExceptionFilterAttribute 的文档? ?例如:

  • 当您设置 context.Result 时会发生什么?它会将该结果序列化为整体响应吗?它会停止应用任何其他过滤器吗?
  • 当您设置 context.ExceptionHandled 时会发生什么?这是否意味着“我已完成异常处理,请将响应发送给客户端”,还是意味着“我已从异常中恢复,继续处理请求”?
  • 你什么时候打电话base.OnExceptionbase.OnExceptionAsync ,在开始还是结束?您是否仅在您的实现不处理给定异常时才调用它?

  • 没有关于此的官方文档,这不是最容易实现的东西,所以有人有 a) 好的文档 - 可能是博客文章,或者 b) 正确的示例实现?

    最佳答案

    Documentation关于 ASP.NET Core 中的过滤器。

    Documentation关于错误处理。

    Exception filters handle unhandled exceptions that occur in controller creation, model binding, action filters, or action methods. They won't catch exceptions that occur in Resource filters, Result filters, or MVC Result execution.+

    To handle an exception, set the ExceptionContext.ExceptionHandled property to true or write a response. This stops propagation of the exception. Note that an Exception filter can't turn an exception into a "success". Only an Action filter can do that.

    Exception filters are good for trapping exceptions that occur within MVC actions, but they're not as flexible as error handling middleware. Prefer middleware for the general case, and use filters only where you need to do error handling differently based on which MVC action was chosen.



    关于“它是否停止应用任何其他过滤器?”:
  • 如果您有未处理的异常,则进一步的管道执行将停止,因为当前方法执行已停止)并且异常将上升到堆栈,直到它被更高级别的 catch 块捕获。


  • 但请记住, ExceptionFilterAttribute 的最终实现逻辑仍在进行中。预计在下一个 .NET Core MVC 1.1.2 中会有一些变化。

    我发现以下有用的解释是 github 问题 (Exception Filters returns an empty body) :

    Have confirmed IActionFilters in MVC 5.2.3 and ASP.NET Core 1.1.0 behave the same. However, IExceptionFilters behave differently w.r.t. setting Result but leaving ExceptionHandled==false. Should remove this special case around setting Result.

    1.1.0 behaviour is also a regression compared to ASP.NET Core 1.0.x.

    Long story about a consistent behaviour for ASP.NET Core:

    • Users can short-circuit most IFilterMetadata implementations by setting Result. But, only on the way in e.g. OnActionExecuting() can short-circuit but OnActionExecuted() cannot.
    • To short-circuit IExceptionFilter implementations (which are only called on the way out), users must set ExceptionHandled==true.
    • Setting ExceptionHandled==true in all IFilterMetadata implementations also ensures an Exception thrown in an action is not rethrown. An overridden Result is used in that case.
    • In a small, intentional deviation from MVC 5.2.3, setting Exception==null is handled identically to setting ExceptionHandled==true.

    关于exception-handling - 如何在 ASP.NET Core 中正确实现 ExceptionFilterAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42708038/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com