2012-01-16 206 views
0

我無法在我的WCF Web API代碼中返回「找不到」的正確HTTP錯誤代碼。這是我的API方法...使用WCF Webapi獲取HTTP 500而不是HTTP 404

[WebInvoke(Method = "GET", UriTemplate = "{id}")] 
    [RequireAuthorisation] 
    public Customer GetCustomer(int id) 
    { 
     var customer = Repository.Find(id); 
     if (customer == null) 
     { 
      throw new HttpResponseException(HttpStatusCode.NotFound); 
     } 
     return customer; 
    } 

我也有一個日誌Handler ...

protected override bool OnTryProvideResponse(Exception exception, ref HttpResponseMessage message) 
    { 
     if (exception != null) 
     { 
      var msg = "Request failed."; 
      _logger.Error(exception, msg); 
     } 

     message = new HttpResponseMessage 
         { 
          StatusCode = HttpStatusCode.InternalServerError 
         }; 

     return true; 
    } 

正在發生的事情是,我收到以下異常...

HttpResponseException 

"The response message returned by the Response property of this exception should be immediately returned to the client. No further handling of the request message is required." 

...這是我的日誌處理程序拾取並將響應狀態代碼更改爲500.

因此,基於閱讀fe w ^博客文章和回答的話,我改變了這個...

 if (customer == null) 
     { 
      WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound(); 
      return null; 
     } 

...但是這現在給我一個200,這顯然是錯誤的。

那麼,正確的做法是什麼?看起來好像拋出HttpResponseException不起作用並且執行後的代碼。

回答

2

的代碼段錯誤處理程序總是在不斷變化的響應消息500不管是什麼,你都明確總是狀態設置爲500

這聽起來像你正在嘗試做的是返回一個500只有當它是一個應用程序錯誤。如果是這種情況,你應該檢查錯誤異常是否是HttpResponseException,並且只返回而不是覆蓋。

至於WebOperationContext,請不要在Web Api中使用它,因爲它基本上沒有任何操作。

希望這會有幫助 Glenn

+0

謝謝。我只是得出同樣的結論。我只需要忽略HttpResponseExceptions :)。關於WebOperationContext的使用,我發現我不得不在操作處理程序中使用它來獲得正確的結果。這聽起來合理嗎?如果沒有,我會發表關於該主題的另一個問題。 – 2012-01-16 20:11:59

+0

你在OP處理程序中使用了什麼? – 2012-01-16 20:22:44