2012-08-23 33 views
4

如果請求到已包含類型Content-Type頭不是由該服務所支持我的Web API服務進行,它會返回一條信息類似如下的500 Internal Server Error狀態代碼:當請求具有不受支持的Content-Type時,如何配置由我的ASP.NET Web API服務返回的狀態代碼?

{"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'MyDto' from content with media type 'application/UnsupportedContentType'.","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger) 
    at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger) 
    at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger) 
    at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) 
    at System.Web.Http.Controllers.HttpActionBinding.<>c__DisplayClass1.<ExecuteBindingAsync>b__0(HttpParameterBinding parameterBinder) 
    at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() 
    at System.Threading.Tasks.TaskHelpers.IterateImpl(IEnumerator`1 enumerator, CancellationToken cancellationToken)"} 

我反而建議返回415 Unsupported Media Type狀態碼,例如,here

如何配置我的服務來做到這一點?

回答

5

下面是我提出的解決此問題的解決方案。

它廣泛地基於描述here的那個,用於在沒有可接受的響應內容類型時發送406不可接受的狀態碼。

public class UnsupportedMediaTypeConnegHandler : DelegatingHandler { 
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
                  CancellationToken cancellationToken) { 
     var contentType = request.Content.Headers.ContentType; 
     var formatters = request.GetConfiguration().Formatters; 
     var hasFormetterForContentType = formatters // 
      .Any(formatter => formatter.SupportedMediaTypes.Contains(contentType)); 

     if (!hasFormetterForContentType) { 
      return Task<HttpResponseMessage>.Factory // 
       .StartNew(() => new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType)); 
     } 

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

和設置服務配置時:

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

注意,這需要的是字符集相匹配也是如此。您可以通過僅檢查標頭的MediaType屬性來放寬此限制。

+2

我已採用此解決方案,但遇到了輕微問題。對於GET請求,代碼仍然運行,並且不會爲'null'content-type(或我的應用程序中的'text/plain')找到Formatter。所以要解決這個問題,我只是簡單地檢查它是否是一個GET請求,如果是這樣,跳過格式化程序檢查... – JTech

0

沒有配置標誌會自動更改狀態碼。您可以創建一個MessageHandler,它可能會檢查「正在發送的響應」並將狀態碼修改爲415.

-1

返回狀態碼的標準方法是從您的操作中返回一個HttpResponseMessage。除了原始內容,您可以將內容包裝在HttpResponseMessage對象中並設置如下狀態:

public System.Net.Http.HttpResponseMessage Getresponse() 
    { 
     return new System.Net.Http.HttpResponseMessage() { Content = new System.Net.Http.StringContent(done.ToString()), StatusCode = System.Net.HttpStatusCode.Conflict }; 
    } 
相關問題