gpt4 book ai didi

asp.net - IExceptionHandler不处理UnsupportedMediaTypeException

转载 作者:行者123 更新时间:2023-12-03 07:54:10 28 4
gpt4 key购买 nike

我已经实现了一个异常处理程序(IExceptionHandler)。当在 Controller 内引发异常时,将调用其HandleAsync方法。
但是,当错误的内容类型与请求一起传递并且格式化程序中引发了UnsupportedMediaTypeException时,不会调用我的处理程序。而是返回默认错误消息
{
"Message": "The request entity's media type...
"ExceptionMessage": "No MediaTypeFormatter ...
...
}

我想处理所有异常。我在这里想念什么?

最佳答案

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

例如。

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

事实证明,在到达WebApi管道时, UnsupportedMediaTypeException实际上已包装在 HttpResponseException中。
HttpResponseException不会拦截 IExceptionHandler,因为它旨在将HttpResponsMessage传输到客户端。框架自动将 UnsupportedMediaTypeException包装为 HttpResponsMessage,并放入 HttpResponseException中。您在HTTP响应中看到的消息为“UnsupportedMediaTypeException”,但这实际上只是 Content( HttpResponsMessage)的 HttpResponseException.Response.Content

关于asp.net - IExceptionHandler不处理UnsupportedMediaTypeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31466370/

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