Mattedatten
Mattedatten

Reputation: 69

C# WCF - Creating custom Message content

I have been inspecting messages sent in a WCF-based system, using the available IClientMessageInspector (and IDispatchMessageInspector).

Currently I'm trying to manually add XML to the message, I cannot manage to get it working.

Situation: Incoming message has a body like

<s:Body>
    <Type xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
    ...
    </Type>
</s:Body>

I want to replace the entire body with custom content, manually structured in a string. I.e., I have a correct XML body in a string, which I want to place within the body of the message.

Is this even possible?

Edit: To further clarify the question: Can I somehow access the "raw text" of the message, and edit it?

Edit2: I.e. I want to keep the original header and all from the incoming message, but want to replace everything between

<body> </body> 

with my custom content which currently resides in a string.

Upvotes: 3

Views: 2891

Answers (1)

lukbl
lukbl

Reputation: 1773

You could use approach similar to one in this blog post https://blogs.msdn.microsoft.com/kaevans/2008/01/08/modify-message-content-with-wcf/

In short you add EndpointBehavior in which you add custom MessageInspector:

Service1Client proxy = new Service1Client();
proxy.Endpoint.Behaviors.Add(new MyBehavior());  

public class MyBehavior : IEndpointBehavior
{
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            MyInspector inspector = new MyInspector();
            clientRuntime.MessageInspectors.Add(inspector);
        }
}

public class MyInspector : IClientMessageInspector
{
    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        var xml = "XML of Body goes here";
        var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
        XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());

        Message replacedMessage = Message.CreateMessage(reply.Version, null, xdr);
        replacedMessage.Headers.CopyHeadersFrom(reply.Headers);
        replacedMessage.Properties.CopyProperties(reply.Properties);
        reply = replacedMessage;
    }
}

EDIT: added MemoryStream initiated with data from a string value.

Upvotes: 3

Related Questions