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

时间:2016-05-27 10:35:58

标签: xml soap message webservice-client

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

1 个答案:

答案 0 :(得分:0)

我一直在寻找如何获取SOAP消息的实际内容,然后将其发送到服务器。

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

首先创建一个Windows窗体应用程序并添加对SOAP Web服务的引用。

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

中的指定创建类

见下面该帖子的副本

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;
    }
}

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

MyServiceClient svc = new MyServiceClient();

然后使用以下代码将行为添加到服务:

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

现在你有了一些可以开始使用的东西了!