2012-01-16 204 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