2012-02-04 168 views
0

我有一个REST服务,我想有一个处理异常异常处理

我的代码如下一个辅助类:

[WebGet(UriTemplate = "/Test/{param}")] 
public Stream Test(string param) 
{ 
     if (param == "Ok") 
      return Process(param); 
     else 
     { 
      RESTException(System.Net.HttpStatusCode.BadRequest, "Param not ok"); 
      return null; 
     } 
} 


private void RESTException(System.Net.HttpStatusCode httpStatusCode, string message) 
{ 
     OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; 
     response.StatusCode = httpStatusCode; // or anything you want 
     response.StatusDescription = message; 
} 

我从浏览器中测试,但是当我通过错误的参数,例如

http://myaddress/Service/Test/badparam 

没有在浏览器中显示。

我的代码有什么问题?

回答

0

我为如下的RESTException,它抛出适当的异常和slsdo表明休息时从浏览器或REST测试客户端提供测试适当的异常信息由REST WCF WebApi

private void RESTException(SelectFault fault, System.Net.HttpStatusCode httpStatusCode) 
    { 
     throw new WebFaultException<string>(fault.ErrorMessage, httpStatusCode); 
    } 
1

变化

RESTException(System.Net.HttpStatusCode.BadRequest, "Param not ok"); 
return null; 

RESTException(System.Net.HttpStatusCode.BadRequest, "Param not ok"); 
return "Param not ok"; 
+0

对不起,web方法应该返回流,而不是字符串。我不想明确返回thr错误消息,而是浏览器报告异常(例如400:BAD请求)。任何建议? – bzamfir 2012-02-04 15:06:09

+0

你确定你正在返回一个400错误吗?使用firebug for Firefox或类似的东西,你可以检查从服务器发回的http头信息,并确保它们包含一个400错误的请求。 – 2012-02-04 15:37:29