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