I’m going to show you how to convert a raw WCF Soap Message to a Memory Stream.
Firstly here is the code:
1: [OperationContract(Action = "*")]
2: public void AddMessage(Message message)3: {4: MessageBuffer buffer = message.CreateBufferedCopy(int.MaxValue);
5:6: Stream stream = new MemoryStream();
7: XmlWriterSettings settings = new XmlWriterSettings
8: {9: Encoding = System.Text.Encoding.UTF810: };11: XmlWriter writer = XmlWriter.Create(stream, settings);12:13: //Create a copy of the message
14: Message message = buffer.CreateMessage();15:16: //Serialize the message to the XmlWriter
17: if (writer != null)18: {19: message.WriteMessage(writer);20: writer.Flush();21: }22:23: stream.Flush();24: stream.Seek(0, SeekOrigin.Begin);25:26: // Save stream to database
27: }
The example above show a generic WCF method that accept any type of message. You might ask why do I ever want to do this? You might want to create a router service for your WCF services or you want to save a copy of a WCF message to a database. Working with an message stream provides allot of flexibility to work with the message contents.
Important points to note of the code is that I create a buffer copy of the original message. The reason is that the body of a message can only be accessed or written to once. If you want to access it more then once it is better to create a buffer copy of the message. From the buffer you can create multiple message instances. If you work with SOAP messages you need to specify the XmlWriterSettings Encoding to UTF8. Otherwise your stream data will become corrupt from the original message structure. Last note is when you create a stream to always flush and move the stream pointer to the beginning of the stream.
Hope this helps and any feedback is welcome.
Cheerio!
Categories: