Tuesday, January 3, 2012

Did you know? - WCF and ClientMessageInspector

Last month I got a feature request to add time logging to the Atlassian .NET SDK. I thought it would be simple until I ran into a peculiar JIRA bug: it turns out that the SOAP response to any call involving time tracking blows up miserably. Curse you JIRA!

After searching the inter webs, I found what the error is on the response and how to fix it. Now what I needed was a way to intercept the response from the server and fix it up before it got passed to the internals of WCF

ClientMessageInspector to the rescue!

First create one of these guys that can update the content of the message
class RemoteWorklogMessageInspector : IClientMessageInspector
{
    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        // update the contents of the response and return a new one with the changes
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        return null;
    }
}
Then you have to register it, which wasn’t totally intuitive. Next you need to create an EndpointBehaviour that adds the inspector to the ClientRuntime.
class RemoteWorklogPatchBehavior : IEndpointBehavior
{    
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new RemoteWorklogMessageInspector());
    }
    
    // other methods from the interface
}
Finally, add the behaviour to the endpoint of the service:
var jiraSoapServiceClient = new JiraSoapServiceClient(binding, endpoint);
jiraSoapServiceClient.Endpoint.Behaviors.Add(new RemoteWorklogPatchBehavior());

Now, whenever a SOAP request goes to JIRA, the response will be inspected and updated if necessary to fix that nasty bug.

Look here for the full source.

0 comments:

Post a Comment