【问题标题】:How to customize error message for 415 status code?如何自定义 415 状态码的错误信息?
【发布时间】:2017-04-06 14:21:42
【问题描述】:

我们已将媒体类型限制为“应用程序/json”。因此,如果请求标头包含“Content-Type:text/plain”,它会响应以下错误消息和状态代码 415。这种行为是预期的,但我想发送带有状态代码 415 的空响应。我们如何在 .网络网络 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)"
}

【问题讨论】:

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


    【解决方案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();
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2018-04-03
        • 2014-12-07
        • 2020-05-29
        • 2017-08-23
        • 1970-01-01
        • 2018-01-31
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        相关资源
        最近更新 更多