How do I customize the error message for status code 415?
We have limited the media type to "application / json". so if the request header contains "Content-Type: text / plain" it responds with below error message and status code 415. This behavior is expected, but I want to send an empty response with status code 415. How can we do this .NET Web API ?
{
"message": "The request entity 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)"
}
source to share
You can create a message handler that will check the content type of the request at the beginning of the pipeline and return a 415 status code with an empty body if the content type of the request 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 your http config message handlers (in WebApiConfig):
config.MessageHandlers.Add(new UnsupportedContentTypeHandler());
And you will get empty responses for all requests that did not provide a content type or did not support a content type.
Note that you can get the supported media types from the global configuration (to avoid duplicating this data):
public UnsupportedContentTypeHandler()
{
supportedContentTypes = GlobalConfiguration.Configuration.Formatters
.SelectMany(f => f.SupportedMediaTypes).ToArray();
}
source to share
You submit your reply in the usual way. Just enter int with the httpstatuscode enumeration.
response.StatusCode = (HttpStatusCode)415;
Also you ask this answer.
HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)415, "Custom Foo error!");
This is a complete example of a custom description error message.
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)415, "Custom Foo error!");
return Task.FromResult(response);
}
source to share