2017-04-05 42 views
3

我们将媒体类型限制为'application/json'。所以如果请求头部包含'Content-Type:text/plain',它会回应下面的错误消息和状态码415.这种行为是预期的,但我想发送状态码为415的空响应。我们如何做到这一点。 Net Web API?如何自定义415状态码的错误消息?

{ 
    "message": "The request entity's media type 'text/plain' is not supported for this resource.", 
    "exceptionMessage": "No MediaTypeFormatter is available to read an object of type 'MyModel' from content with media type 'text/plain'.", 
    "exceptionType": "System.Net.Http.UnsupportedMediaTypeException", 
    "stackTrace": " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)" 
} 

回答

1

您可以创建消息处理程序将检查内容类型的要求,管道早,空体返回415状态码如果不支持请求的内容类型:

public class UnsupportedContentTypeHandler : DelegatingHandler 
{ 
    private readonly MediaTypeHeaderValue[] supportedContentTypes = 
    { 
     new MediaTypeHeaderValue("application/json") 
    }; 

    protected async override Task<HttpResponseMessage> SendAsync(
     HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     var contentType = request.Content.Headers.ContentType; 
     if (contentType == null || !supportedContentTypes.Contains(contentType)) 
      return request.CreateResponse(HttpStatusCode.UnsupportedMediaType); 

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

添加此消息处理程序HTTP配置的消息处理程序(在WebApiConfig):

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

,你会得到所有的空响应没有提供内容类型或不支持的内容类型的请求。

请注意,您可以从全局配置支持的媒体类型(以避免重复这个数据):

public UnsupportedContentTypeHandler() 
{ 
    supportedContentTypes = GlobalConfiguration.Configuration.Formatters 
           .SelectMany(f => f.SupportedMediaTypes).ToArray(); 
} 
0

您以正常方式发送您的回复。只需使用httpstatuscode enum投射int即可。

response.StatusCode = (HttpStatusCode)415; 

您还设置了这样的回复。

HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)415, "Custom Foo error!"); 

这是自定义描述错误消息的完整示例。

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
    { 
     HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)415, "Custom Foo error!"); 
     return Task.FromResult(response); 
    }