IExceptionHandler 不处理 UnsupportedMediaTypeException
IExceptionHandler does not handle UnsupportedMediaTypeException
我已经实现了异常处理程序 (IExceptionHandler
)。它的 HandleAsync
方法在控制器内部抛出异常时被调用。
但是,当随请求传递错误的内容类型并且在格式化程序中抛出 UnsupportedMediaTypeException
时,不会调用我的处理程序。而是返回默认错误消息
{
"Message": "The request entity's media type...
"ExceptionMessage": "No MediaTypeFormatter ...
...
}
我想处理所有异常。我在这里错过了什么?
您需要使用全局 ExceptionFilterAttribute
捕获它并过滤 HttpResponseException
,而不是 UnsupportedMediaTypeException
。
例如
httpConfiguration.Filters.Add(new MyHttpResponseExceptionFilterAttribute());
事实证明,UnsupportedMediaTypeException
在到达 WebApi 管道时实际上已包含在 HttpResponseException
中。
HttpResponseException
不会被 IExceptionHandler
拦截,因为它旨在将 HttpResponsMessage 传输到客户端。 UnsupportedMediaTypeException
被框架自动包装到 HttpResponsMessage
中,并抛出到 HttpResponseException
中。您在 HTTP 响应中看到的消息显示 "UnsupportedMediaTypeException",但实际上它只是 HttpResponsMessage
(HttpResponseException.Response.Content
) 的 Content
。
我已经实现了异常处理程序 (IExceptionHandler
)。它的 HandleAsync
方法在控制器内部抛出异常时被调用。
但是,当随请求传递错误的内容类型并且在格式化程序中抛出 UnsupportedMediaTypeException
时,不会调用我的处理程序。而是返回默认错误消息
{
"Message": "The request entity's media type...
"ExceptionMessage": "No MediaTypeFormatter ...
...
}
我想处理所有异常。我在这里错过了什么?
您需要使用全局 ExceptionFilterAttribute
捕获它并过滤 HttpResponseException
,而不是 UnsupportedMediaTypeException
。
例如
httpConfiguration.Filters.Add(new MyHttpResponseExceptionFilterAttribute());
事实证明,UnsupportedMediaTypeException
在到达 WebApi 管道时实际上已包含在 HttpResponseException
中。
HttpResponseException
不会被 IExceptionHandler
拦截,因为它旨在将 HttpResponsMessage 传输到客户端。 UnsupportedMediaTypeException
被框架自动包装到 HttpResponsMessage
中,并抛出到 HttpResponseException
中。您在 HTTP 响应中看到的消息显示 "UnsupportedMediaTypeException",但实际上它只是 HttpResponsMessage
(HttpResponseException.Response.Content
) 的 Content
。