开发者

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

开发者 https://www.devze.com 2023-01-23 10:41 出处:网络
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

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;
    }
开发者_如何学运维

}


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());


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.


I suspect ToString will return what you are getting. ToString is often used for debugging, and hence only shows you basic information about the object. You need to do something like this in ConvertToXDocument:

XDocument x = XDocument.Load(xdr);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号