当请求具有不受支持的内容类型时,如何配置 ASP.NET Web API 服务返回的状态代码?

2024-02-22

如果向我的 Web API 服务发出的请求具有Content-Type标头包含该服务不支持的类型,它返回500 Internal Server Error带有类似以下消息的状态代码:

{"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'MyDto' from content with media type 'application/UnsupportedContentType'.","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)
   at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)
   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)
   at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
   at System.Web.Http.Controllers.HttpActionBinding.<>c__DisplayClass1.<ExecuteBindingAsync>b__0(HttpParameterBinding parameterBinder)
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Threading.Tasks.TaskHelpers.IterateImpl(IEnumerator`1 enumerator, CancellationToken cancellationToken)"}

相反,我更愿意返回一个415 Unsupported Media Type建议的状态代码,例如,here http://brockallen.com/2012/05/14/http-status-codes-for-rest/.

我如何配置我的服务来执行此操作?


这是我针对这个问题提出的解决方案。

它大致基于所描述的here http://blog.ploeh.dk/2012/04/24/VendorMediaTypesWithTheASPNETWebAPI.aspx用于在没有可接受的响应内容类型时发送 406 Not Acceptable 状态代码。

public class UnsupportedMediaTypeConnegHandler : DelegatingHandler {
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                           CancellationToken cancellationToken) {
        var contentType = request.Content.Headers.ContentType;
        var formatters = request.GetConfiguration().Formatters;
        var hasFormetterForContentType = formatters //
            .Any(formatter => formatter.SupportedMediaTypes.Contains(contentType));

        if (!hasFormetterForContentType) {
            return Task<HttpResponseMessage>.Factory //
                .StartNew(() => new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

        return base.SendAsync(request, cancellationToken);
    }
}

设置服务配置时:

config.MessageHandlers.Add(new UnsupportedMediaTypeConnegHandler());

请注意,这也要求字符集匹配。您可以通过仅检查MediaType标头的属性。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当请求具有不受支持的内容类型时,如何配置 ASP.NET Web API 服务返回的状态代码? 的相关文章

随机推荐