【问题标题】:Exception handling in REST serviceREST 服务中的异常处理
【发布时间】:2012-04-03 21:57:12
【问题描述】:

我有一个 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

浏览器中没有任何显示。

我的代码有什么问题?

【问题讨论】:

    标签: .net exception rest exception-handling weboperationcontext


    【解决方案1】:

    改变

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

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

    【讨论】:

    • 抱歉,web 方法应该返回 Stream,而不是字符串。我不想明确返回错误消息,而是浏览器报告异常(例如 400:BAD Request)。有什么建议吗?
    • 您确定要返回 400 错误吗?使用 Firefox 的 firebug 或类似的东西,您可以检查从服务器发回的 http 标头,并确保它们包含 400 错误请求。
    【解决方案2】:

    我将 RESTException 更改如下,当从浏览器或 REST WCF WebApi 提供的 REST 测试客户端测试 REST 时,它会引发正确的异常,并且 slsdo 会显示正确的异常信息

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

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 2011-07-10
      • 2015-08-17
      相关资源
      最近更新 更多