开发者

Capture response when a service returns a 500 error using WCF

I'm getting data from a 3rd party web service using REST (using WebHttpBinding and WebHttpBehavior). When I pass an invalid parameter in the querystring, the service responds with a 500 status and describes the problem. The response looks something l开发者_如何学运维ike this:

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>

I would really like to be able to capture that error message. My WCF client looks like this:

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);
    }
}

When I catch the exception that is thrown, that data is nowhere to be found. It just says, "System.ServiceModel.CommunicationException: Internal Server Error".

I tried creating a custom behavior and added a message inspector, but my custom message inspector code doesn't get executed before the exception is thrown (it does get executed if no exception is thrown).


I finally figured it out. Creating a custom behavior and adding a message inspector is the way that I needed to do it. I just needed to add my custom behavior before the WebHttpBehavior. Then I can look at the whole response and throw my own exception with all the data in it!


(Can't get my test project to actually send the HTTP 500, only seems to do that when I don't want it to ;-)

In the off-chance that this will help you, try wrapping you client service call and inspect the response in the debugger to see if it contains the error string you are trying to capture.

    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];
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜