Handle exception on IClientMessageInspector

681 Views Asked by At

I have calling wcf service and I implemented IClientMessageInspector interface.

I want to handle error on AfterReceiveReply. The fault exception should always return 200 status code with custom message and error code. It should not throw any exception on service call.

public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            if (reply.IsFault)
            {
                // wrap message with http status code 200 and return content as exception model like status code, exception message;
            }
        }

I want to handle exception and it always return response without any exception that I will handle in cusumer code.

Thanks

1

There are 1 best solutions below

1
On

You could try HttpResponseMessageProperty, it contains the status code of the returned Message.

 if (reply.IsFault)
        {
            if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
            {
                HttpResponseMessageProperty pro = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
                pro.StatusCode = System.Net.HttpStatusCode.OK;

            }
            else
            {
                reply.Properties.Add(HttpResponseMessageProperty.Name, new HttpResponseMessageProperty { StatusCode = System.Net.HttpStatusCode.OK });
            }
        }

But the message has returned by server, if server throws exception, you may not be able to receive the message in the AfterReceiveReply method.

If this doesn't work, I suggest you could do this using IDispatchMessageInspector at server side to change the status code before sending response. (If you have control over server side) http://mark.mymonster.nl/2011/02/10/make-use-of-wcf-faultcontracts-in-silverlight-clients/