如何在.NET WCF中使用MessageBuffer对象的WriteMessage(Stream stream)方法?

时间:2013-06-20 15:15:31

标签: .net wcf serialization soap xmldocument

在试图弄清楚如何将.NET System.ServiceModel.Channels.Message对象转换为XmlDocument时,我想我可以这样做:

Message message = Message.CreateMessage(messageVersion, "SOAPAction");

using(var messageBuffer = message.CreateBufferedCopy(int.MaxValue))
{
    var stream = new MemoryStream();
    using(var xmlWriter = XmlWriter.Create(stream))
    {
        var xmlDocument = new XmlDocument();

        messageBuffer.WriteMessage(stream);
        stream.Flush();

        stream.Position = 0;
        xmlDocument.Load(stream);
        stream.Close();

        Debug.Writeline(xmlDocument.OuterXml);
    }
}

但是,这会导致xmlDocument.Load(stream)出错:

"Data at the root level is invalid. Line 1, position 1."

我现在意识到我应该将Message对象的WriteMessage与XmlWriter对象结合使用,如下所示:

Message message = Message.CreateMessage(messageVersion, "SOAPAction");
using(var messageBuffer = message.CreateBufferedCopy(int.MaxValue))
{
    var stream = new MemoryStream();
    using(var xmlWriter = XmlWriter.Create(stream))
    {
        var xmlDocument = new XmlDocument();

        messageBuffer.CreateMessage().WriteMessage(xmlWriter);
        xmlWriter.Flush();
        stream.Flush();

        stream.Position = 0;
        xmlDocument.Load(stream);

        xmlWriter.Close();
        stream.Close();

        Debug.WriteLine(xmlDocument.OuterXml);
    }
}

我确定我缺少一些基本观点,但这引出了我的问题 - MessageBuffer对象上的WriteMessage(Stream流)有什么用处?

0 个答案:

没有答案