Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF message body showing <s:Body>... stream ...</s:Body> after modification

Tags:

wcf

Trying to use MessageInspector to modify the message before the wcf service through the proxy. However while debugging the message body does not gets copied and body shows

 <s:Body>... stream ...</s:Body>

What is the problem with the code?

public class CustomWCFMessageInspector : IClientMessageInspector
{
    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        request = ModifyMessage(request);
        return null;
    }

    private Message ModifyMessage(Message oldMessage)
    {
        Message newMessage = null;
        MessageBuffer msgbuf = oldMessage.CreateBufferedCopy(int.MaxValue);

        Message tmpMessage = msgbuf.CreateMessage();
        XmlDictionaryReader xdr = tmpMessage.GetReaderAtBodyContents();

        XDocument xd = ConvertToXDocument(xdr);

        EmitTags(xd);

        var ms = new MemoryStream();
        var xw = XmlWriter.Create(ms);
        xd.Save(xw);

        xw.Flush();
        xw.Close();

        ms.Position = 0;
        XmlReader xr = XmlReader.Create(ms);

        newMessage = Message.CreateMessage(tmpMessage.Version, null, xr);
        newMessage.Headers.CopyHeadersFrom(tmpMessage);
        newMessage.Properties.CopyProperties(tmpMessage.Properties);

        return newMessage;
    }

}

like image 684
dhinesh Avatar asked Nov 05 '10 13:11

dhinesh


2 Answers

Here is solution: if you call Message.ToString() you will get

..stream..

Instead use System.Xml.XmlWriter. Here is a sample:

MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
Message msg = buffer.CreateMessage();
StringBuilder sb = new StringBuilder();
using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(sb))
{
    msg.WriteMessage(xw);
    xw.Close();
}
Console.WriteLine("Message Received:\n{0}", sb.ToString());
like image 99
Denis Kochnev Avatar answered Oct 20 '22 01:10

Denis Kochnev


The problem was that the newMessage body was not shown in the watch window after doing ToString()

Created the buffered copy of the message to be shown in the debugger.

MessageBuffer messageBuffer = newMessage.CreateBufferedCopy(int.MaxValue);
Message message = messageBuffer.CreateMessage();

So there is No problem in the code. It is just that the debugger is not showing the message body as mentioned in the link below

http://msdn.microsoft.com/en-us/library/ms734675(v=VS.90).aspx

in the Accessing the Message Body for Debugging section.

like image 37
dhinesh Avatar answered Oct 20 '22 00:10

dhinesh