【问题标题】:IExceptionHandler does not handle UnsupportedMediaTypeExceptionIExceptionHandler 不处理 UnsupportedMediaTypeException
【发布时间】:2015-10-06 14:48:15
【问题描述】:

我已经实现了一个异常处理程序 (IExceptionHandler)。它的HandleAsync 方法在控制器内部抛出异常时被调用。 但是,当请求传递了错误的内容类型并且在格式化程序中抛出了 UnsupportedMediaTypeException 时,我的处理程序不会被调用。而是返回默认错误消息

{ "Message": "The request entity's media type... "ExceptionMessage": "No MediaTypeFormatter ... ... }

我想处理所有异常。我在这里错过了什么?

【问题讨论】:

    标签: asp.net error-handling exception-handling asp.net-web-api2


    【解决方案1】:

    您需要使用全局ExceptionFilterAttribute 捕获它,并过滤HttpResponseException,而不是UnsupportedMediaTypeException

    例如

    httpConfiguration.Filters.Add(new MyHttpResponseExceptionFilterAttribute());
    

    事实证明,UnsupportedMediaTypeException 在到达 WebApi 管道时实际上已被包裹在 HttpResponseException 中。

    HttpResponseException 不会被IExceptionHandler 拦截,因为它旨在将 HttpResponsMessage 传输到客户端。 UnsupportedMediaTypeException 被框架自动包装成一个HttpResponsMessage,并抛出一个HttpResponseException。您在 HTTP 响应中看到的消息是“UnsupportedMediaTypeException”,但这实际上只是 HttpResponsMessage (HttpResponseException.Response.Content) 的 Content

    【讨论】:

    • 谢谢@jordan-morris。 +1 用于解释发生了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多