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

问题描述

| 我正在使用REST(使用
WebHttpBinding
WebHttpBehavior
)从第三方Web服务获取数据。当我在查询字符串中传递无效参数时,服务将以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:内部服务器错误\”。 我尝试创建自定义行为并添加了消息检查器,但是我的自定义消息检查器代码在引发异常之前不会执行(如果未引发异常,则不会执行)。     

解决方法

        我终于弄明白了。创建自定义行为并添加消息检查器是我要做的方法。我只需要在ѭ1之前添加自定义行为即可。然后,我可以查看整个响应并在其中包含所有数据的情况下抛出我自己的异常!     ,        (无法让我的测试项目实际发送HTTP 500,仅在我不希望它发送时才这样做;-) 在不大可能帮助您的情况下,请尝试包装客户端服务调用并检查调试器中的“ 5”,以查看其中是否包含您要捕获的错误字符串。
    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];
    }