1 private string MessageToString(ref Message message) 2 { 3 WebContentFormat messageFormat = this.GetMessageContentFormat(message); 4 MemoryStream ms = new MemoryStream(); 5 XmlDictionaryWriter writer = null; 6 switch (messageFormat) 7 { 8 case WebContentFormat.Default: 9 case WebContentFormat.Xml: 10 writer = XmlDictionaryWriter.CreateTextWriter(ms); 11 break; 12 case WebContentFormat.Json: 13 writer = JsonReaderWriterFactory.CreateJsonWriter(ms); 14 break; 15 case WebContentFormat.Raw: 16 return this.ReadRawBody(ref message); 17 } 18 19 message.WriteMessage(writer); 20 writer.Flush(); 21 string messageBody = Encoding.UTF8.GetString(ms.ToArray()); 22 23 ms.Position = 0; 24 // 这里需要将message重新写入 25 XmlDictionaryReader reader; 26 if (messageFormat == WebContentFormat.Json) 27 { 28 reader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max); 29 } 30 else 31 { 32 reader = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max); 33 } 34 35 Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version); 36 newMessage.Properties.CopyProperties(message.Properties); 37 message = newMessage; 38 39 return messageBody; 40 } 41 42 private WebContentFormat GetMessageContentFormat(Message message) 43 { 44 WebContentFormat format = WebContentFormat.Default; 45 if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name)) 46 { 47 WebBodyFormatMessageProperty bodyFormat; 48 bodyFormat = (WebBodyFormatMessageProperty)message.Properties[WebBodyFormatMessageProperty.Name]; 49 format = bodyFormat.Format; 50 } 51 52 return format; 53 } 54 55 private string ReadRawBody(ref Message message) 56 { 57 XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); 58 bodyReader.ReadStartElement("Binary"); 59 byte[] bodyBytes = bodyReader.ReadContentAsBase64(); 60 string messageBody = Encoding.UTF8.GetString(bodyBytes); 61 62 // Now to recreate the message 63 MemoryStream ms = new MemoryStream(); 64 XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms); 65 writer.WriteStartElement("Binary"); 66 writer.WriteBase64(bodyBytes, 0, bodyBytes.Length); 67 writer.WriteEndElement(); 68 writer.Flush(); 69 ms.Position = 0; 70 XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(ms, XmlDictionaryReaderQuotas.Max); 71 Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version); 72 newMessage.Properties.CopyProperties(message.Properties); 73 message = newMessage; 74 75 return messageBody; 76 }
时间: 2024-10-12 15:31:34