调用Web服务时,是否有一种简单的方法来获取请求的肥皂消息和响应的肥皂消息?

时间:2019-04-26 14:12:34

标签: c# xml wcf soap wsdl

我想调用一个Web服务,我想以肥皂消息的形式获取请求和响应对象。

var response = client.invoke(parameter);

我想以某种方式使消息发送和接收。

1 个答案:

答案 0 :(得分:1)

基于Carlos Figueira的MSDN文章WCF Extensibility – Message Inspectors,一种选择是使用MessageInspector。

创建一个实现EndBehaviorClientMessageInspector的类。缓冲请求和回复消息,以便以后使用。在此示例中,我在控制台中打印它们。

这是组合的实现:

// using System.ServiceModel.Description;
// using System.ServiceModel.Dispatcher;
// using System.ServiceModel.Channels;
// using System.ServiceModel
public class InspectBehaviorAndnspector : IEndpointBehavior, IClientMessageInspector
{

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(this);
    }

    public MessageBuffer RequestBuffer;
    public MessageBuffer ReplyBuffer;

    public void AfterReceiveReply(ref Message reply, object correlationState){
       // messages are read only
       ReplyBuffer = reply.CreateBufferedCopy(2048);
       // so recreate the message after it was buffered
       reply = ReplyBuffer.CreateMessage();
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel){
       // messages are read only
       RequestBuffer = request.CreateBufferedCopy(2048);
       // so recreate the message after it was buffered
       request = RequestBuffer.CreateMessage();
       return "42";
    }

    // not needed for client
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(ServiceEndpoint sep) 
    {
    }
    public void AddBindingParameters(ServiceEndpoint sep, BindingParameterCollection bpc)
    {
    }
}

现在在您的client实例上,假设它是从ClientBase派生的,您可以执行以下操作:

var inspector = new InspectBehaviorAndnspector();
client.Endpoint.Behaviors.Add(inspector);

// this is your call
var response = client.invoke(parameter);

// either do a ToString
Console.WriteLine(inspector.RequestBuffer.CreateMessage().ToString());
// or Write it with XmlWriter
var sb = new StringBuilder();
using(var xw = XmlWriter.Create(sb, new XmlWriterSettings {Indent =true})) {
    inspector.ReplyBuffer.CreateMessage().WriteMessage(xw);
}
Console.WriteLine(sb.ToString());

我已经在带有添加服务的示例中运行了此命令,这就是我的结果:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/ISelfHostTest/Add</Action>
  </s:Header>
  <s:Body>
    <Add xmlns="http://tempuri.org/">
      <x>3</x>
      <y>2</y>
    </Add>
  </s:Body>
</s:Envelope>

<?xml version="1.0" encoding="utf-16"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <AddResponse xmlns="http://tempuri.org/">
      <AddResult>5</AddResult>
    </AddResponse>
  </s:Body>
</s:Envelope>