C#实现SOAP调用WebService

最近写了一个SOA服务,开始觉得别人拿到我的服务地址,然后直接添加引用就可以使用了,结果"大牛"告知不行。

让我写一个SOAP调用服务的样例,我有点愣了,因为没做过这方面的,于是搞到了一个Demo,然后学习了下。

学习如下:

在.Net中有一个对象:WebRequest它可以在后台直接请求服务的方法

第一步

var webRequest = (HttpWebRequest)WebRequest.Create(this.Uri);
webRequest.Headers.Add("SOAPAction", String.Format(""{0}"", this.SoapAction));
webRequest.ContentType = "text/xml;charset="utf-8"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.Credentials = this.Credentials;

A:上述代码中,有一个SOAPAction,这个是你在IIS中部署好服务后,访问服务,如下图:

图中告知了使用者:SOAPAction:"http://tempuri.org/ProcessFlowRequest"

B:webRequest.Credentials = this.Credentials;

是调用服务的凭据

第二步

上述了解后,需要拼接SOAP请求的XML如图中看到的那个SOAP信息

<?xml version='1.0' encoding='utf-8'?>
<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
  <soap:Body>
    <{0} xmlns='{1}'>{2}</{0}>
  </soap:Body>
</soap:Envelope>

把图片中对应的信息替换到{X}对应的位置,信息拼接就完成了!


第三步

            var webRequest = (HttpWebRequest)WebRequest.Create(this.Uri);
            webRequest.Headers.Add("SOAPAction", String.Format(""{0}"", this.SoapAction));
            webRequest.ContentType = "text/xml;charset="utf-8"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            webRequest.Credentials = this.Credentials;

            // 写入请求SOAP信息
            using (var requestStream = webRequest.GetRequestStream())
            {
                using (var textWriter = new StreamWriter(requestStream))
                {
                    var envelope = SoapHelper.MakeEnvelope(this.SoapAction, this.Arguments.ToArray());
                }
            }

            // 获取SOAP请求返回
            return webRequest.GetResponse();

这个就能获取到请求返回的XML!

其实用了才知道,原来很简单!

在说明一个使用情况,在调用时,会报404错误,抛出异常信息为:服务器未能识别 HTTP 标头 SOAPAction

解决方法:

给.NET的WebService类(即.asmx文件下的类)添加属性[SoapDocumentService(RoutingStyle=SoapServiceRoutingStyle.RequestElement)]

样例:

百度网盘: http://pan.baidu.com/s/1hquuXHa

CSDN: http://download.csdn.net/detail/hater22/7490147

原文地址:https://www.cnblogs.com/kimi-gyj/p/3784483.html