using System; using System.IO; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.Text; using System.Xml; namespace dk.nsi.seal { public class MessageToString : IEndpointBehavior { private readonly Action request; private readonly Action response; public MessageToString(Action request, Action response) { this.request = request; this.response = response; } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) => clientRuntime.ClientMessageInspectors.Add(new MessageToStringInspector(request, response)); public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { } public void Validate(ServiceEndpoint endpoint) { } } internal class MessageToStringInspector : IClientMessageInspector { private readonly Action request; private readonly Action response; public MessageToStringInspector(Action request, Action response) { this.request = request; this.response = response; } public void AfterReceiveReply(ref Message reply, object correlationState) => response(ToString(ref reply)); public object BeforeSendRequest(ref Message request, IClientChannel channel) { this.request(ToString(ref request)); return null; } static string ToString(ref Message m) { // copy the message into a working buffer. MessageBuffer mb = m.CreateBufferedCopy(int.MaxValue); // re-create the original message, because "copy" changes its state. m = mb.CreateMessage(); Stream s = new MemoryStream(); XmlWriter xw = XmlWriter.Create(s); mb.CreateMessage().WriteMessage(xw); xw.Flush(); s.Position = 0; byte[] bXML = new byte[s.Length]; s.Read(bXML, 0, (int)s.Length); // sometimes bXML[] starts with a BOM var skip = bXML[0] != (byte)'<' ? 3 : 0; return Encoding.UTF8.GetString(bXML, skip, bXML.Length - skip); } } }