当服务使用WCF返回500错误时捕获响应

时间:2011-06-14 16:40:15

标签: c# wcf exception-handling

我使用REST从第三方Web服务获取数据(使用WebHttpBindingWebHttpBehavior)。当我在查询字符串中传递无效参数时,服务以500状态响应并描述问题。响应看起来像这样:

HTTP/1.1 500 Internal Server Error
Date: Tue, 14 Jun 2011 16:12:48 GMT
... more headers

<Error>Invalid integer value for ID</Error>

我真的希望能够捕获该错误消息。我的WCF客户端如下所示:

public class DataClient : ClientBase<IDataClient>, IDataClient
{
    public DataClient (string endpointAddress)
        : base(new WebHttpBinding(), new EndpointAddress(endpointAddress))
    {
        this.Endpoint.Behaviors.Add(new WebHttpBehavior());
    }

    public string GetData(string id)
    {
        // This is where the exception is thrown
        return base.Channel.GetData(id);
    }
}

当我捕获抛出的异常时,无法找到该数据。它只是说,“System.ServiceModel.CommunicationException:Internal Server Error”。

我尝试创建自定义行为并添加了一个消息检查器,但是在抛出异常之前我的自定义消息检查器代码没有执行(如果没有抛出异常,它会执行)。

2 个答案:

答案 0 :(得分:3)

我终于明白了。创建自定义行为和添加消息检查器是我需要的方法。我只需要在WebHttpBehavior之前添加自定义行为。然后我可以查看整个响应并将其自身的异常与其中的所有数据一起抛出!

答案 1 :(得分:0)

(无法让我的测试项目实际发送HTTP 500,只是在我不想要的时候才会这样做;)

如果这对您有帮助,请尝试包装客户端服务调用并检查调试器中的response以查看它是否包含您尝试捕获的错误字符串。

    using (new OperationContextScope(service1.InnerChannel))
    {
        try
        {
            result = service1.GetData("5");
        }
        catch (System.Exception e)
        {
            string msg = e.ToString();
        }
        HttpResponseMessageProperty response = (HttpResponseMessageProperty)
            OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name];
    }
相关问题