asp.net-web-api - 当请求具有不受支持的 Content-Type 时,如何配置我的 ASP.NET Web API 服务返回的状态代码?

标签 asp.net-web-api content-negotiation

如果对我的 Web API 服务发出的请求具有 Content-Type包含该服务不支持的类型的 header ,它返回 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 .

我如何配置我的服务来做到这一点?

最佳答案

这是我想出的解决这个问题的方法。

它广泛地基于所描述的 here用于在没有可接受的响应内容类型时发送 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 来放松此限制。头的属性。

关于asp.net-web-api - 当请求具有不受支持的 Content-Type 时,如何配置我的 ASP.NET Web API 服务返回的状态代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12098097/

相关文章:

c# - ASP.NET 网络 API : Perform Search on Table using HTTP GET Method and Linq to SQL Dynamically

c# - 使用 RouteAttribute 或隐式路由时的 WebApi 路径差异

C# WebAPI 垃圾回收

调用 ASP.NET Web API 时出现 AJAX 504

javascript - 使用 Breeze.js 进行非事务性 SaveChanges

php - 如何根据浏览器语言重定向用户

c# - 如何得到 Nancy 谈判代表的回应?

java - Spring API 中是否有更好的基于 Accept Header 的内容协商方法?

java - 使用 spring-boot : Content Negotiation failed! 未找到类型返回值的转换器

c# - 是否有 C# 或 .NET 类来处理 HTTP 内容协商?