如何配置我的的ASP.NET Web API服务返回的状态代码时请求有不支持的内容类型?(How d

2019-09-21 14:13发布

如果请求到具有我的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的状态码推荐,如这里 。

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

Answer 1:

这里是我想出了这个问题的解决方案。

它广泛的基础上所描述的在这里用于发送406无法接受的状态代码时没有可接受的响应内容类型。

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头的性能。



Answer 2:

没有配置标志会自动改变的状态代码。 您可以创建一个的MessageHandler这或许可以勾选“响应发送出去”,并修改状态码415。



Answer 3:

返回状态代码的标准方法是从你的行动返回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 };
    }


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