4

如果向我的 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

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

4

3 回答 3

5

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

它广泛基于此处描述的用于在没有可接受的响应内容类型时发送 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您可以通过仅检查标头的属性来放松此限制。

于 2012-08-23T20:29:03.287 回答
0

没有会自动更改状态代码的配置标志。您可以创建一个 MessageHandler,它可能会检查“正在发送的响应”并将状态代码修改为 415。

于 2012-08-23T20:20:27.997 回答
-1

返回状态码的标准方法是从您的操作中返回 HttpResponseMessage。您可以将内容包装在 HttpResponseMessage 对象中,并像这样设置状态,而不是原始内容:

public System.Net.Http.HttpResponseMessage Getresponse()
    {
        return new System.Net.Http.HttpResponseMessage() { Content = new System.Net.Http.StringContent(done.ToString()), StatusCode = System.Net.HttpStatusCode.Conflict };
    }
于 2012-08-24T07:07:48.147 回答