我有一个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 :(得分:1)
更改
RESTException(System.Net.HttpStatusCode.BadRequest, "Param not ok");
return null;
到
RESTException(System.Net.HttpStatusCode.BadRequest, "Param not ok");
return "Param not ok";
答案 1 :(得分:0)
我更改了RESTException,如下所示,当从浏览器或REST WCF WebApi提供的REST测试客户端测试REST时,抛出正确的异常并且slsdo显示正确的异常信息
private void RESTException(SelectFault fault, System.Net.HttpStatusCode httpStatusCode)
{
throw new WebFaultException<string>(fault.ErrorMessage, httpStatusCode);
}