我有几种方法的WCF服务。我想记录来自客户端的原始请求,无论它是如何发送的。我使用以下方法
public Message CreateMessage(Message message)
{
MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);
var messageCopy = buffer.CreateMessage();
Console.WriteLine(messageCopy.ToString());
return buffer.CreateMessage();
}
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
request = CreateMessage(request);
return null;
}
我在结果和字符串中获取XML但是使用标题我希望字符串在正文中但根本没有标题。在这方面,有人可以帮助我。
答案 0 :(得分:1)
最后,我将其解决并获得覆盖Body Writer类的解决方案。请在下面找到详细的解决方案。
namespace WcfServiceRaw
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract(ReplyAction = "ResponseToGetDataRequest")]
Message GetData();
}
}
namespace WcfServiceRaw
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class Service1 : IService1
{
public Message GetData()
{
// Create body
TestDataWriter body = new TestDataWriter("<test>data</test>");
// Create messatge
MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
Message msg = Message.CreateMessage(ver, "ResponseToGetDataRequest", body);
//Debug.WriteLine(msg.ToString());
return msg;
}
}
class TestDataWriter : BodyWriter
{
string _data;
public TestDataWriter(string data)
: base(false)
{
_data = data;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteRaw(_data);
}
}
客户是:
namespace WcfClientRaw
{
class Program
{
static void Main(string[] args)
{
//IMyContract proxy = ChannelFactory<IMyContract>.CreateChannel(new BasicHttpBinding(), new EndpointAddress(address));
WcfServiceRaw.Service1Client proxy = new WcfServiceRaw.Service1Client();
using (proxy as IDisposable)
{
Message msg = proxy.GetData();
Console.WriteLine(msg.ToString());
Console.WriteLine();
XmlDictionaryReader xdr = msg.GetReaderAtBodyContents();
//string exp = "<test>data</test>";
string act = xdr.ReadOuterXml();
//Debug.Assert(exp == act);
Console.WriteLine(act);
Console.ReadLine();
}
}
}
}
答案 1 :(得分:0)
您可以在System.ServiceModel.Channel.Message类上使用GetReaderAtBodyContents。
var reader = message.GetReaderAtBodyContents();
Console.WriteLine(reader.ReadOuterXml());