2014-10-28 68 views
3

我需要爲基於SOAP的Web服務開發.NET 4.5客戶端。問題是正在開發這些基於SOAP的服務的公司不提供WSDL。但是他們確實提供了請求響應模式(XSD文件)。由於沒有WSDL,我無法添加Web引用並獲取自動生成的客戶端代理代碼。如何在不添加Web引用的情況下調用SOAP Web服務

是否有任何.NET 4.5庫可以用來創建這些SOAP基本服務調用?它也需要支持SOAP 1.1和SOAP附件。

+0

一個選項是使用WCF並使用「通道層「。您仍然需要您想使用的WebService的接口。 – 2014-10-28 07:44:44

+1

...或者只是自己創建WSDL並使用它來「添加Web引用」。 – ChrFin 2014-10-28 07:45:40

+0

在你的情況下創建WSDL是個好主意,因爲它可以節省你的時間來處理可序列化的實體。如果這些方法配置了消息級別的安全性,那麼這種方法對於服務也是安全的。 – tom 2014-10-28 09:27:07

回答

6

如果您不希望創建的WSDL文件某種原因,下面的例子可以用來手動構建一個SOAP HTTP請求:

var url = Settings.Default.URL; //'Web service URL' 
var action = Settings.Default.SOAPAction; //the SOAP method/action name 

var soapEnvelopeXml = CreateSoapEnvelope(); 
var soapRequest = CreateSoapRequest(url, action); 
InsertSoapEnvelopeIntoSoapRequest(soapEnvelopeXml, soapRequest); 

using (var stringWriter = new StringWriter()) 
{ 
    using (var xmlWriter = XmlWriter.Create(stringWriter)) 
    { 
     soapEnvelopeXml.WriteTo(xmlWriter); 
     xmlWriter.Flush(); 
    } 
} 

// begin async call to web request. 
var asyncResult = soapRequest.BeginGetResponse(null, null); 

// suspend this thread until call is complete. You might want to 
// do something usefull here like update your UI. 
var success = asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)); 

if (!success) return null; 

// get the response from the completed web request. 
using (var webResponse = soapRequest.EndGetResponse(asyncResult)) 
{ 
    string soapResult; 
    var responseStream = webResponse.GetResponseStream(); 
    if (responseStream == null) 
    { 
     return null; 
    } 
    using (var reader = new StreamReader(responseStream)) 
    { 
     soapResult = reader.ReadToEnd(); 
    } 
    return soapResult; 
} 

private static HttpWebRequest CreateSoapRequest(string url, string action) 
{ 
    var webRequest = (HttpWebRequest)WebRequest.Create(url); 
    webRequest.Headers.Add("SOAPAction", action); 
    webRequest.ContentType = "text/xml;charset=\"utf-8\""; 
    webRequest.Accept = "text/xml"; 
    webRequest.Method = "POST"; 
    return webRequest; 
} 

private static XmlDocument CreateSoapEnvelope() 
{ 
    var soapEnvelope = new XmlDocument(); 
    soapEnvelope.LoadXml(Settings.Default.SOAPEnvelope); //the SOAP envelope to send 
    return soapEnvelope; 
} 

private static void InsertSoapEnvelopeIntoSoapRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) 
{ 
    using (Stream stream = webRequest.GetRequestStream()) 
    { 
     soapEnvelopeXml.Save(stream); 
    } 
} 
+0

非常感謝你馬特。猜測我會建立在此基礎上,看看如何在請求中加入SOAP附件。非常感謝。 – Harindaka 2014-10-30 07:01:07

+0

我有錯。[聽](http://stackoverflow.com/questions/36998808/call-service-with-url-mistake)。可以幫我嗎? – shahroz 2016-05-03 08:12:50

相關問題