SoapHttpClientProtocol.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. //
  2. // System.Web.Services.Protocols.SoapHttpClientProtocol.cs
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. // Miguel de Icaza ([email protected])
  7. // Lluis Sanchez Gual ([email protected])
  8. //
  9. // Copyright (C) Tim Coleman, 2002
  10. // Copyright (C) Ximian, Inc, 2003
  11. //
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System.IO;
  33. using System.Net;
  34. using System.Web;
  35. using System.Xml;
  36. using System.Text;
  37. using System.Reflection;
  38. using System.Web.Services;
  39. using System.Diagnostics;
  40. using System.Runtime.CompilerServices;
  41. using System.Web.Services.Description;
  42. using System.Web.Services.Discovery;
  43. using System.Xml.Serialization;
  44. using System.Xml.Schema;
  45. using System.Collections;
  46. using System.Threading;
  47. namespace System.Web.Services.Protocols
  48. {
  49. public class SoapHttpClientProtocol : HttpWebClientProtocol
  50. {
  51. SoapTypeStubInfo type_info;
  52. #if NET_2_0
  53. WsiClaims conformanceClaims;
  54. SoapProtocolVersion soapVersion;
  55. #endif
  56. #region SoapWebClientAsyncResult class
  57. internal class SoapWebClientAsyncResult: WebClientAsyncResult
  58. {
  59. public SoapWebClientAsyncResult (WebRequest request, AsyncCallback callback, object asyncState)
  60. : base (request, callback, asyncState)
  61. {
  62. }
  63. public SoapClientMessage Message;
  64. public SoapExtension[] Extensions;
  65. }
  66. #endregion
  67. #region Constructors
  68. public SoapHttpClientProtocol ()
  69. {
  70. type_info = (SoapTypeStubInfo) TypeStubManager.GetTypeStub (this.GetType (), "Soap");
  71. }
  72. #endregion // Constructors
  73. #region Methods
  74. protected IAsyncResult BeginInvoke (string methodName, object[] parameters, AsyncCallback callback, object asyncState)
  75. {
  76. SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (methodName);
  77. SoapWebClientAsyncResult ainfo = null;
  78. try
  79. {
  80. SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
  81. message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
  82. WebRequest request = GetRequestForMessage (uri, message);
  83. ainfo = new SoapWebClientAsyncResult (request, callback, asyncState);
  84. ainfo.Message = message;
  85. ainfo.Extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
  86. ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);
  87. }
  88. catch (Exception ex)
  89. {
  90. if (ainfo != null)
  91. ainfo.SetCompleted (null, ex, false);
  92. }
  93. return ainfo;
  94. }
  95. void AsyncGetRequestStreamDone (IAsyncResult ar)
  96. {
  97. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
  98. try
  99. {
  100. SendRequest (ainfo.Request.EndGetRequestStream (ar), ainfo.Message, ainfo.Extensions);
  101. ainfo.Request.BeginGetResponse (new AsyncCallback (AsyncGetResponseDone), ainfo);
  102. }
  103. catch (Exception ex)
  104. {
  105. ainfo.SetCompleted (null, ex, true);
  106. }
  107. }
  108. void AsyncGetResponseDone (IAsyncResult ar)
  109. {
  110. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
  111. WebResponse response = null;
  112. try {
  113. response = GetWebResponse (ainfo.Request, ar);
  114. }
  115. catch (WebException ex) {
  116. response = ex.Response;
  117. HttpWebResponse http_response = response as HttpWebResponse;
  118. if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError) {
  119. ainfo.SetCompleted (null, ex, true);
  120. return;
  121. }
  122. }
  123. catch (Exception ex) {
  124. ainfo.SetCompleted (null, ex, true);
  125. return;
  126. }
  127. try {
  128. object[] result = ReceiveResponse (response, ainfo.Message, ainfo.Extensions);
  129. ainfo.SetCompleted (result, null, true);
  130. }
  131. catch (Exception ex) {
  132. ainfo.SetCompleted (null, ex, true);
  133. }
  134. }
  135. protected object[] EndInvoke (IAsyncResult asyncResult)
  136. {
  137. if (!(asyncResult is SoapWebClientAsyncResult)) throw new ArgumentException ("asyncResult is not the return value from BeginInvoke");
  138. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) asyncResult;
  139. lock (ainfo)
  140. {
  141. if (!ainfo.IsCompleted) ainfo.WaitForComplete ();
  142. if (ainfo.Exception != null) throw ainfo.Exception;
  143. else return (object[]) ainfo.Result;
  144. }
  145. }
  146. public void Discover ()
  147. {
  148. BindingInfo bnd = (BindingInfo) type_info.Bindings [0];
  149. DiscoveryClientProtocol discoverer = new DiscoveryClientProtocol ();
  150. discoverer.Discover (Url);
  151. foreach (object info in discoverer.AdditionalInformation)
  152. {
  153. System.Web.Services.Discovery.SoapBinding sb = info as System.Web.Services.Discovery.SoapBinding;
  154. if (sb != null && sb.Binding.Name == bnd.Name && sb.Binding.Namespace == bnd.Namespace) {
  155. Url = sb.Address;
  156. return;
  157. }
  158. }
  159. string msg = string.Format ("The binding named '{0}' from namespace '{1}' was not found in the discovery document at '{2}'", bnd.Name, bnd.Namespace, Url);
  160. throw new Exception (msg);
  161. }
  162. protected override WebRequest GetWebRequest (Uri uri)
  163. {
  164. return base.GetWebRequest (uri);
  165. }
  166. WebRequest GetRequestForMessage (Uri uri, SoapClientMessage message)
  167. {
  168. WebRequest request = GetWebRequest (uri);
  169. request.Method = "POST";
  170. WebHeaderCollection headers = request.Headers;
  171. headers.Add ("SOAPAction", "\"" + message.Action + "\"");
  172. request.ContentType = message.ContentType + "; charset=utf-8";
  173. return request;
  174. }
  175. void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)
  176. {
  177. using (s) {
  178. if (extensions != null) {
  179. s = SoapExtension.ExecuteChainStream (extensions, s);
  180. message.SetStage (SoapMessageStage.BeforeSerialize);
  181. SoapExtension.ExecuteProcessMessage (extensions, message, true);
  182. }
  183. XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);
  184. WebServiceHelper.WriteSoapMessage (xtw, type_info, message.MethodStubInfo.Use, message.MethodStubInfo.RequestSerializer, message.Parameters, message.Headers);
  185. if (extensions != null) {
  186. message.SetStage (SoapMessageStage.AfterSerialize);
  187. SoapExtension.ExecuteProcessMessage (extensions, message, true);
  188. }
  189. xtw.Flush ();
  190. xtw.Close ();
  191. }
  192. }
  193. //
  194. // TODO:
  195. // Handle other web responses (multi-output?)
  196. //
  197. object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
  198. {
  199. SoapMethodStubInfo msi = message.MethodStubInfo;
  200. HttpWebResponse http_response = response as HttpWebResponse;
  201. if (http_response != null)
  202. {
  203. HttpStatusCode code = http_response.StatusCode;
  204. if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError)) {
  205. string msg = "The request failed with HTTP status {0}: {1}";
  206. msg = String.Format (msg, (int) code, code);
  207. throw new WebException (msg, null, WebExceptionStatus.ProtocolError, http_response);
  208. }
  209. }
  210. //
  211. // Remove optional encoding
  212. //
  213. string ctype;
  214. Encoding encoding = WebServiceHelper.GetContentEncoding (response.ContentType, out ctype);
  215. if (ctype != "text/xml")
  216. WebServiceHelper.InvalidOperation (
  217. "Content is not 'text/xml' but '" + response.ContentType + "'",
  218. response, encoding);
  219. message.ContentType = ctype;
  220. message.ContentEncoding = encoding.WebName;
  221. Stream stream = response.GetResponseStream ();
  222. if (extensions != null) {
  223. stream = SoapExtension.ExecuteChainStream (extensions, stream);
  224. message.SetStage (SoapMessageStage.BeforeDeserialize);
  225. SoapExtension.ExecuteProcessMessage (extensions, message, false);
  226. }
  227. // Deserialize the response
  228. StreamReader reader = new StreamReader (stream, encoding, false);
  229. XmlTextReader xml_reader = new XmlTextReader (reader);
  230. SoapHeaderCollection headers;
  231. object content;
  232. WebServiceHelper.ReadSoapMessage (xml_reader, type_info, msi.Use, msi.ResponseSerializer, out content, out headers);
  233. if (content is Fault)
  234. {
  235. Fault fault = (Fault) content;
  236. SoapException ex = new SoapException (fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
  237. message.SetException (ex);
  238. }
  239. else
  240. message.OutParameters = (object[]) content;
  241. message.SetHeaders (headers);
  242. message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);
  243. if (extensions != null) {
  244. message.SetStage (SoapMessageStage.AfterDeserialize);
  245. SoapExtension.ExecuteProcessMessage (extensions, message, false);
  246. }
  247. if (message.Exception == null)
  248. return message.OutParameters;
  249. else
  250. throw message.Exception;
  251. }
  252. protected object[] Invoke (string method_name, object[] parameters)
  253. {
  254. SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);
  255. SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
  256. message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
  257. SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
  258. WebResponse response;
  259. try
  260. {
  261. WebRequest request = GetRequestForMessage (uri, message);
  262. SendRequest (request.GetRequestStream (), message, extensions);
  263. response = GetWebResponse (request);
  264. }
  265. catch (WebException ex)
  266. {
  267. response = ex.Response;
  268. HttpWebResponse http_response = response as HttpWebResponse;
  269. if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
  270. throw ex;
  271. }
  272. return ReceiveResponse (response, message, extensions);
  273. }
  274. #if NET_2_0
  275. [MonoTODO ("Do something with this")]
  276. [System.Runtime.InteropServices.ComVisible(false)]
  277. [Obsolete]
  278. public WsiClaims ConformanceClaims {
  279. get { return conformanceClaims; }
  280. set { conformanceClaims = value; }
  281. }
  282. [MonoTODO ("Do something with this")]
  283. [System.Runtime.InteropServices.ComVisible(false)]
  284. public SoapProtocolVersion SoapVersion {
  285. get { return soapVersion; }
  286. set { soapVersion = value; }
  287. }
  288. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback)
  289. {
  290. InvokeAsync (methodName, parameters, callback, null);
  291. }
  292. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback, object userState)
  293. {
  294. InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
  295. BeginInvoke (methodName, parameters, new AsyncCallback (InvokeAsyncCallback), info);
  296. }
  297. void InvokeAsyncCallback (IAsyncResult ar)
  298. {
  299. InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;
  300. SoapWebClientAsyncResult sar = (SoapWebClientAsyncResult) ar;
  301. InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);
  302. if (info.Context != null)
  303. info.Context.SendOrPost (info.Callback, args);
  304. else
  305. info.Callback (args);
  306. }
  307. #endif
  308. #endregion // Methods
  309. }
  310. }