如何将SOAP消息视为Web服务方法调用?

时间:2013-12-18 06:54:21

标签: .net web-services soap

我希望看到我发送到Web服务的内容是在.Net中调用方法。例如:

var list = service.SomeWebMethd(req);

我想看看我发送给Web服务的SOAP消息。我该怎么办?

1 个答案:

答案 0 :(得分:1)

经过大量搜索和提问后,我设法专门为C#编写了这个类,它抓取了SOAP请求和响应信封。希望这也可以帮到你。

首先创建一个新类并复制粘贴此代码,只需更改命名空间。

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;

//Set namespace to the project name
namespace yourProjectName // <-- EDIT
{
    class SOAPRequestResponse : IEndpointBehavior
    {
        public string lastRequestXML
        {
            get
            {
                return soapInspector.lastRequestXML;
            }
        }

        public string lastResponseXML
        {
            get
            {
                return soapInspector.lastResponseXML;
            }
        }

        private MyMessageInspector soapInspector = new MyMessageInspector();

        public void AddBindingParameters(ServiceEndpoint endPoint, BindingParameterCollection bindingParameters)
        {

        }

        public void ApplyDispatchBehavior(ServiceEndpoint endPoint, EndpointDispatcher endPointDispatcher)
        {

        }

        public void Validate(ServiceEndpoint endPoint)
        {

        }

        public void ApplyClientBehavior(ServiceEndpoint endPoint, ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(soapInspector);
        }

        public class MyMessageInspector : IClientMessageInspector
        {
            public string lastRequestXML { get; private set; }
            public string lastResponseXML { get; private set; }

            public void AfterReceiveReply(ref Message reply, object corActionState)
            {
                lastResponseXML = reply.ToString();
            }

            public object BeforeSendRequest(ref Message request, IClientChannel channel)
            {
                lastRequestXML = request.ToString();
                return request;
            }
        }
    }
}

其次,您需要在主表单中创建SOAPRequestRespone的新实例。

SOAPRequestResponse soapENV = new SOAPRequestResponse();

然后,您必须将其添加到代理类中,如此(也在主窗体中):

service.Endpoint.Behaviors.Add(soapENV);

最后,您可以将请求和响应包络分配给字符串变量,如下所示:

string request = soapENV.lastRequestXML;
string response = soapENV.lastResponseXML;

希望这对你也有帮助。您可以使用其他工具,如SOAPUI。