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不起作用並且執行後的代碼。
謝謝。我只是得出同樣的結論。我只需要忽略HttpResponseExceptions :)。關於WebOperationContext的使用,我發現我不得不在操作處理程序中使用它來獲得正確的結果。這聽起來合理嗎?如果沒有,我會發表關於該主題的另一個問題。 – 2012-01-16 20:11:59
你在OP處理程序中使用了什麼? – 2012-01-16 20:22:44