如何在不添加Web引用的情况下调用SOAP Web服务

本文关键字:Web 情况下 调用 SOAP 服务 引用 添加 | 更新日期: 2023-09-27 18:28:00

我需要为基于SOAP的web服务开发一个.NET 4.5客户端。问题是开发这些基于SOAP的服务的公司不提供WSDL。但是,它们确实提供了请求-响应模式(XSD文件)。由于没有WSDL,我无法添加web引用并自动生成客户端代理代码。

有没有.NET 4.5库可以用来进行这些基于SOAP的服务调用?它还需要支持SOAP 1.1和SOAP附件。

如何在不添加Web引用的情况下调用SOAP Web服务

如果出于某种原因不想创建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);
    }
}
相关文章: