在客户端应用程序发送之前获取实际的 SOAP 消息 (XML)

Get actual SOAP message (XML) before it's send by the Client application

我想获取 XML SOAP 消息的实际内容,该消息将使用 .NET 客户端应用程序中的 SOAP webservcie 引用发送到服务器。

我一直在思考如何获取发送到服务器的 SOAP 消息的实际内容。

终于找到了答案,我想在这里用非常简单的代码分享——基于https://wcfpro.wordpress.com/2011/03/29/iclientmessageinspector/

首先创建一个 Windows Forms 应用程序并添加对 SOAP 网络服务的引用。

然后按照 https://wcfpro.wordpress.com/2011/03/29/iclientmessageinspector/

中的指定创建 类

请参阅下面的副本 post

public class MyBehavior : IEndpointBehavior
{

    public void AddBindingParameters(
        ServiceEndpoint endpoint,
        BindingParameterCollection bindingParameters)
    {
    }

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

    public void ApplyDispatchBehavior(
        ServiceEndpoint endpoint, 
        EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(
        ServiceEndpoint endpoint)
    {
    }
}

public class MyMessageInspector : IClientMessageInspector
{
    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
        // use 'reply.ToString()' te get content and do something with is
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        // use 'request.ToString()' te get content and do something with is
        return null;
    }
}

现在是最重要的部分,我花了一段时间才弄明白。 当您创建网络服务实例时:

MyServiceClient svc = new MyServiceClient();

然后使用此代码将行为添加到服务中:

svc.ChannelFactory.Endpoint.Behaviors.Add(new MyBehavior());

现在您可以开始使用了!