Search code examples
xmlsoapmessagewebservice-client

Get actual SOAP message (XML) before it's send by the Client application


I want to get the actual content of the XML SOAP message, which will be send to the server using a SOAP webservcie reference in a .NET Client application.


Solution

  • I've been searching my head of on how to get the actual content of a SOAP message, which is send to the server.

    Finally I found the answer, which I would like to share here with very simple code - based on https://wcfpro.wordpress.com/2011/03/29/iclientmessageinspector/

    First create an Windows Forms application and add a reference to a SOAP webservice.

    Then create the classes as specified in https://wcfpro.wordpress.com/2011/03/29/iclientmessageinspector/

    See below a copy out of that post

    public class MyBehavior : IEndpointBehavior
    {
    
        public void AddBindingParameters(
            ServiceEndpoint endpoint,
            BindingParameterCollection bindingParameters)
        {
        }
    
        public void ApplyClientBehavior(
            ServiceEndpoint endpoint, 
            ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new MyMessageInspector());
        }
    
        public void ApplyDispatchBehavior(
            ServiceEndpoint endpoint, 
            EndpointDispatcher endpointDispatcher)
        {
        }
    
        public void Validate(
            ServiceEndpoint endpoint)
        {
        }
    }
    
    public class MyMessageInspector : IClientMessageInspector
    {
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            // use 'reply.ToString()' te get content and do something with is
        }
    
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // use 'request.ToString()' te get content and do something with is
            return null;
        }
    }
    

    And now comes the most important part, which took me a while to figure out. When you create instance of the webservice:

    MyServiceClient svc = new MyServiceClient();
    

    Then add the behavior to the service using this code:

    svc.ChannelFactory.Endpoint.Behaviors.Add(new MyBehavior());
    

    And now you have something you can start to work with!