Capture response when a service returns a 500 error using WCF

我怕爱的太早我们不能终老 提交于 2019-12-24 02:33:07

问题


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 like 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).


回答1:


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!




回答2:


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


来源:https://stackoverflow.com/questions/6346965/capture-response-when-a-service-returns-a-500-error-using-wcf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!