C# WCF IClientMessageInspector.BeforeSendRequest修改请求
我正在尝试修改WCF服务中的请求C# WCF IClientMessageInspector.BeforeSendRequest修改请求,c#,wcf,C#,Wcf,我正在尝试修改WCF服务中的请求 public object BeforeSendRequest(ref Message request, IClientChannel channel) { string xmlRequest = request.ToString(); XDocument xDoc = XDocument.Parse(xmlRequest); //Some request modifications //Here i have XML wha
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
string xmlRequest = request.ToString();
XDocument xDoc = XDocument.Parse(xmlRequest);
//Some request modifications
//Here i have XML what in want to send
request = Message.CreateMessage(request.Version, request.Headers.Action, WhatHere?);
request.Headers.Clear();
return null;
}
但我不知道我可以在CreateMessage
中设置什么,或者可能是将XML设置为请求的不同方式 您可以传递表示已修改消息的对象。下面是本文中的一个示例
使用此方法是否可以在信封的开头(打开标记之前)和结束标记之后添加内容?“我不能让它工作。@maracuja juice你能提供一个例子或问一个新问题吗?我在这里得到了一些HashedData而不是格式良好的数据:xdoc.Load(xdr);这是编码吗?
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
Console.WriteLine("====SimpleMessageInspector+BeforeSendRequest is called=====");
//modify the request send from client(only customize message body)
request = TransformMessage2(request);
return null;
}
//only read and modify the Message Body part
private Message TransformMessage2(Message oldMessage)
{
Message newMessage = null;
//load the old message into XML
MessageBuffer msgbuf = oldMessage.CreateBufferedCopy(int.MaxValue);
Message tmpMessage = msgbuf.CreateMessage();
XmlDictionaryReader xdr = tmpMessage.GetReaderAtBodyContents();
XmlDocument xdoc = new XmlDocument();
xdoc.Load(xdr);
xdr.Close();
//transform the xmldocument
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("a", "urn:test:datacontracts");
XmlNode node = xdoc.SelectSingleNode("//a:StringValue", nsmgr);
if(node!= null) node.InnerText = "[Modified in SimpleMessageInspector]" + node.InnerText;
MemoryStream ms = new MemoryStream();
XmlWriter xw = XmlWriter.Create(ms);
xdoc.Save(xw);
xw.Flush();
xw.Close();
ms.Position = 0;
XmlReader xr = XmlReader.Create(ms);
//create new message from modified XML document
newMessage = Message.CreateMessage(oldMessage.Version, null,xr );
newMessage.Headers.CopyHeadersFrom(oldMessage);
newMessage.Properties.CopyProperties(oldMessage.Properties);
return newMessage;
}