如何自定义415状态代码的错误消息?

时间:2017-04-05 20:54:23

标签: c# asp.net-web-api2

我们已将媒体类型限制为' application / json'。因此,如果请求标头包含' Content-Type:text / plain',则会响应以下错误消息和状态代码415.此行为是预期的,但我想发送状态代码为415的空响应。怎么能我们在.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)"
}

2 个答案:

答案 0 :(得分:1)

如果不支持请求内容类型,您可以创建消息处理程序,它将在管道中提前检查请求的内容类型,并返回415状态代码和空体:

ids = await asyncio.gather(*[self.generate_url(url) for url in urls])

将此消息处理程序添加到http配置的消息处理程序(位于 WebApiConfig ):

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

对于未提供内容类型或内容类型不受支持的所有请求,您将获得空响应。

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

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

答案 1 :(得分:0)

您以正常方式发送回复。只需使用httpstatuscode枚举转换为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);
    }