asp.net – 返回状态代码4xx,用于具有无效/不支持的Content-Type(如text / plain)的客户端请求

我使用ASP.NET Web API(包含在ASP.NET MVC 4中)实现了RESTful API.

当客户端使用不受支持的Content-Type(如“text / plain”)请求我的服务时,我会收到以下异常:

System.InvalidOperationException: No MediaTypeFormatter is available
to read an object of type […] from content with media type
‘text/plain’.

并且我的服务返回HTTP状态代码500并记录/报告错误(我正在使用ELMAH).

不幸的是,我找不到一种简单的方法来“捕获”这种不受支持的客户端请求.恕我直言,该服务应返回状态代码,如404(未找到)或400(错误请求),因为错误不是服务器错误(但客户端错误).

在另一个SO问题中,我找到了这个答案How do I configure the status code returned by my ASP.NET Web API service when the request has an unsupported Content-Type?,它通过实现自定义DelegatingHandler显示了一个可能的解决方案.

所以我的问题是:我错过了什么吗?是否存在针对此问题的ASP.NET Web API内置功能…

最佳答案 我最终使用类似于此实现的自定义DelegatingHandler“修复”了该问题

How do I configure the status code returned by my ASP.NET Web API service when the request has an unsupported Content-Type?.

你可以在这里找到我的实现:http://blog.janjonas.net/2012-09-05/asp_net-mvc_4_rc-web-api-return-http-status-code-4xx-invalidoperationexception-no-mediatypeformatter-available-read-object-type-content-media-type

点赞