简体   繁体   中英

How to customize error message for 415 status code?

We have restricted media type to 'application/json'. so if request header contains 'Content-Type: text/plain', it responds with below error message and status code 415. This behavior is expected but I would like to send empty response with status code 415. How can we do that in .Net Web API?

{
   "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)"
}

You can create message handler which will check content type of request early in pipeline and return 415 status code with empty body if request content type is not supported:

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);
    }
}

Add this message handler to message handlers of http configuration (at WebApiConfig ):

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

And you will get empty responses for all requests which didn't provide content type or have unsupported content type.

Note that you can get supported media types from global configuration (to avoid duplicating this data):

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

You send your response with normal way. Just cast int with httpstatuscode enum.

response.StatusCode = (HttpStatusCode)415;

Also you set response like this.

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

This is full example of customized description error message.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM