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

时间:2014-10-28 07:39:15

标签: c# .net wcf soap soap-client

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

是否有可用于进行这些SOAP基本服务调用的.NET 4.5库?它也需要支持SOAP 1.1和SOAP附件。

1 个答案:

答案 0 :(得分:7)

如果由于某种原因您不想创建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);
    }
}