我有以下用于修改WCF消息的遗留代码:
private void ModifyReceivedRequest(ref Message message)
{
MemoryStream ms = new MemoryStream();
Encoding encoding = Encoding.UTF8;
XmlWriterSettings writerSettings = new XmlWriterSettings { Encoding = encoding };
writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
writerSettings.Indent = true;
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(ms, writerSettings));
message.WriteBodyContents(writer);
writer.Flush();
var array = ms.ToArray(); // 56896306 size
string messageBodyString = encoding.GetString(array);
// change the message body
messageBodyString = messageBodyString.Replace("</applicationStructureData>", "</applicationStructureData><srcDataArray>");
messageBodyString = messageBodyString.Replace("</applicationData>", "</srcDataArray></applicationData>");
ms = new MemoryStream(encoding.GetBytes(messageBodyString));
XmlReader bodyReader = XmlReader.Create(ms);
Message originalMessage = message;
message = Message.CreateMessage(originalMessage.Version, null, bodyReader);
message.Headers.CopyHeadersFrom(originalMessage);
}
encoding.GetString(array)
会抛出OutOfMemoryException
。有没有其他方法可以在不使用这些转换的情况下修改邮件正文?
答案 0 :(得分:0)
解决问题的方法是摆脱对字符串的转换。
private void ModifyReceivedRequest(ref Message message)
{
MemoryStream ms = new MemoryStream();
Encoding encoding = Encoding.UTF8;
XmlWriterSettings writerSettings = new XmlWriterSettings { Encoding = encoding };
writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
writerSettings.Indent = true;
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(ms, writerSettings));
message.WriteBodyContents(writer);
writer.Flush();
ms.Position = 0;
XmlDocument xDoc = new XmlDocument();
xDoc.Load(ms);
ms.Flush();
ms = new MemoryStream();
// XML stuff
GC.Collect();
xDoc.Save(ms);
ms.Position = 0;
XmlReader bodyReader = XmlReader.Create(ms);
Message originalMessage = message;
message = Message.CreateMessage(originalMessage.Version, null, bodyReader);
message.Headers.CopyHeadersFrom(originalMessage);
}