最近写了一个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!
其实用了才知道,原来很简单!
样例:
本文探讨了在.NET环境中实现SOAP服务调用的过程,包括创建HTTP请求、添加SOAPAction头、设置请求参数、拼接SOAP XML请求以及接收响应。通过实例演示,展示了从理论到实践的完整流程,并提供了相关资源链接。
3649

被折叠的 条评论
为什么被折叠?



