Tuesday, March 18, 2008 10:36 PM
kolbis
Modify The Message Body
Here is an example of how to create a message inspector that will inspect every message that the client sends and modify the message body:
public class ClientOutputMessageInspector : IClientMessageInspector
{
#region IClientMessageInspector Members
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
return;
}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
{
string action = request.Headers.GetHeader<string>("Action", request.Headers[0].Namespace);
if (action.Contains("SendMessage"))
{
XmlDocument doc = new XmlDocument();
MemoryStream ms = new MemoryStream();
XmlWriter writer = XmlWriter.Create(ms);
request.WriteMessage(writer);
writer.Flush();
ms.Position = 0;
doc.Load(ms);
ChangeMessage(doc);
ms.SetLength(0);
writer = XmlWriter.Create(ms);
doc.WriteTo(writer);
writer.Flush();
ms.Position = 0;
XmlReader reader = XmlReader.Create(ms);
request = Message.CreateMessage(reader, int.MaxValue, request.Version);
}
return null;
}
void ChangeMessage(XmlDocument doc)
{
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
nsManager.AddNamespace("tempuri", "http://tempuri.org/");
XmlNode node = doc.SelectSingleNode("//s:Body/tempuriendMessage/tempuri:text", nsManager);
if (node != null)
{
XmlText text = node.FirstChild as XmlText;
if (text != null)
{
text.Value = "Modified: " + text.Value;
}
}
}
#endregion
}
תגים:WCF