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