C#實現SOAP調用WebService

最近寫了一個SOA服務,開始以爲別人拿到個人服務地址,而後直接添加引用就能夠使用了,結果"大牛"告知不行。web

讓我寫一個SOAP調用服務的樣例,我有點愣了,由於沒作過這方面的,因而搞到了一個Demo,而後學習了下。服務器

 

學習以下:學習

在.Net中有一個對象:WebRequest它能夠在後臺直接請求服務的方法this

第一步spa

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中部署好服務後,訪問服務,以下圖:
.net

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

B:webRequest.Credentials = this.Credentials;orm

是調用服務的憑據xml

第二步對象

上述瞭解後,須要拼接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

相關文章
相關標籤/搜索