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

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM