HttpSoapWebServiceHandler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. //
  2. // System.Web.Services.Protocols.HttpSoapWebServiceHandler.cs
  3. //
  4. // Author:
  5. // Lluis Sanchez Gual ([email protected])
  6. //
  7. // Copyright (C) Ximian, Inc. 2003
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Net;
  31. using System.Web;
  32. using System.Xml;
  33. using System.Text;
  34. using System.IO;
  35. using System.Reflection;
  36. using System.Xml.Serialization;
  37. using System.Web.Services.Description;
  38. namespace System.Web.Services.Protocols
  39. {
  40. internal class HttpSoapWebServiceHandler: WebServiceHandler
  41. {
  42. SoapTypeStubInfo _typeStubInfo;
  43. SoapExtension[] _extensionChainHighPrio;
  44. SoapExtension[] _extensionChainMedPrio;
  45. SoapExtension[] _extensionChainLowPrio;
  46. SoapMethodStubInfo methodInfo;
  47. SoapServerMessage requestMessage = null;
  48. public HttpSoapWebServiceHandler (Type type): base (type)
  49. {
  50. _typeStubInfo = (SoapTypeStubInfo) TypeStubManager.GetTypeStub (ServiceType, "Soap");
  51. }
  52. public override bool IsReusable
  53. {
  54. get { return false; }
  55. }
  56. internal override MethodStubInfo GetRequestMethod (HttpContext context)
  57. {
  58. try
  59. {
  60. requestMessage = DeserializeRequest (context.Request);
  61. return methodInfo;
  62. }
  63. catch (Exception ex)
  64. {
  65. SerializeFault (context, requestMessage, ex);
  66. return null;
  67. }
  68. }
  69. public override void ProcessRequest (HttpContext context)
  70. {
  71. Context = context;
  72. SoapServerMessage responseMessage = null;
  73. try
  74. {
  75. if (requestMessage == null) {
  76. requestMessage = DeserializeRequest (context.Request);
  77. #if NET_2_0
  78. object soapVer = context.Items ["WebServiceSoapVersion"];
  79. if (soapVer != null)
  80. requestMessage.SetSoapVersion ((SoapProtocolVersion) soapVer);
  81. #endif
  82. }
  83. if (methodInfo != null && methodInfo.OneWay) {
  84. context.Response.BufferOutput = false;
  85. context.Response.StatusCode = 202;
  86. context.Response.Flush ();
  87. context.Response.Close ();
  88. Invoke (context, requestMessage);
  89. } else {
  90. responseMessage = Invoke (context, requestMessage);
  91. SerializeResponse (context.Response, responseMessage);
  92. }
  93. }
  94. catch (Exception ex)
  95. {
  96. if (methodInfo != null && methodInfo.OneWay) {
  97. context.Response.StatusCode = 500;
  98. context.Response.Flush ();
  99. context.Response.Close ();
  100. } else {
  101. SerializeFault (context, requestMessage, ex);
  102. }
  103. }
  104. finally {
  105. IDisposable disp = requestMessage.Server as IDisposable;
  106. requestMessage = null;
  107. if (disp != null)
  108. disp.Dispose();
  109. }
  110. }
  111. SoapServerMessage DeserializeRequest (HttpRequest request)
  112. {
  113. Stream stream = request.InputStream;
  114. //using (stream)
  115. //{
  116. string soapAction = null;
  117. string ctype;
  118. Encoding encoding = WebServiceHelper.GetContentEncoding (request.ContentType, out ctype);
  119. #if NET_2_0
  120. if (ctype != "text/xml" && ctype != "application/soap+xml")
  121. #else
  122. if (ctype != "text/xml")
  123. #endif
  124. throw new WebException ("Content is not XML: " + ctype);
  125. object server = CreateServerInstance ();
  126. SoapServerMessage message = new SoapServerMessage (request, server, stream);
  127. message.SetStage (SoapMessageStage.BeforeDeserialize);
  128. message.ContentType = ctype;
  129. // If the routing style is SoapAction, then we can get the method information now
  130. // and set it to the SoapMessage
  131. if (_typeStubInfo.RoutingStyle == SoapServiceRoutingStyle.SoapAction)
  132. {
  133. soapAction = request.Headers ["SOAPAction"];
  134. if (soapAction == null) throw new SoapException ("Missing SOAPAction header", SoapException.ClientFaultCode);
  135. methodInfo = _typeStubInfo.GetMethodForSoapAction (soapAction);
  136. if (methodInfo == null) throw new SoapException ("Server did not recognize the value of HTTP header SOAPAction: " + soapAction, SoapException.ClientFaultCode);
  137. message.MethodStubInfo = methodInfo;
  138. }
  139. // Execute the high priority global extensions. Do not try to execute the medium and
  140. // low priority extensions because if the routing style is RequestElement we still
  141. // don't have method information
  142. _extensionChainHighPrio = SoapExtension.CreateExtensionChain (_typeStubInfo.SoapExtensions[0]);
  143. stream = SoapExtension.ExecuteChainStream (_extensionChainHighPrio, stream);
  144. SoapExtension.ExecuteProcessMessage (_extensionChainHighPrio, message, stream, false);
  145. // If the routing style is RequestElement, try to get the method name from the
  146. // stream processed by the high priority extensions
  147. if (_typeStubInfo.RoutingStyle == SoapServiceRoutingStyle.RequestElement)
  148. {
  149. MemoryStream mstream;
  150. byte[] buffer = null;
  151. if (stream.CanSeek)
  152. {
  153. buffer = new byte [stream.Length];
  154. for (int n=0; n<stream.Length;)
  155. n += stream.Read (buffer, n, (int)stream.Length-n);
  156. mstream = new MemoryStream (buffer);
  157. }
  158. else
  159. {
  160. buffer = new byte [500];
  161. mstream = new MemoryStream ();
  162. int len;
  163. while ((len = stream.Read (buffer, 0, 500)) > 0)
  164. mstream.Write (buffer, 0, len);
  165. mstream.Position = 0;
  166. buffer = mstream.ToArray ();
  167. }
  168. soapAction = ReadActionFromRequestElement (new MemoryStream (buffer), encoding);
  169. stream = mstream;
  170. methodInfo = (SoapMethodStubInfo) _typeStubInfo.GetMethod (soapAction);
  171. message.MethodStubInfo = methodInfo;
  172. }
  173. // Whatever routing style we used, we should now have the method information.
  174. // We can now notify the remaining extensions
  175. if (methodInfo == null) throw new SoapException ("Method '" + soapAction + "' not defined in the web service '" + _typeStubInfo.LogicalType.WebServiceName + "'", SoapException.ClientFaultCode);
  176. _extensionChainMedPrio = SoapExtension.CreateExtensionChain (methodInfo.SoapExtensions);
  177. _extensionChainLowPrio = SoapExtension.CreateExtensionChain (_typeStubInfo.SoapExtensions[1]);
  178. stream = SoapExtension.ExecuteChainStream (_extensionChainMedPrio, stream);
  179. stream = SoapExtension.ExecuteChainStream (_extensionChainLowPrio, stream);
  180. SoapExtension.ExecuteProcessMessage (_extensionChainMedPrio, message, stream, false);
  181. SoapExtension.ExecuteProcessMessage (_extensionChainLowPrio, message, stream, false);
  182. // Deserialize the request
  183. StreamReader reader = new StreamReader (stream, encoding, false);
  184. XmlTextReader xmlReader = new XmlTextReader (reader);
  185. try
  186. {
  187. object content;
  188. SoapHeaderCollection headers;
  189. WebServiceHelper.ReadSoapMessage (xmlReader, methodInfo, SoapHeaderDirection.In, out content, out headers);
  190. message.InParameters = (object []) content;
  191. message.SetHeaders (headers);
  192. }
  193. catch (Exception ex)
  194. {
  195. throw new SoapException ("Could not deserialize Soap message", SoapException.ClientFaultCode, ex);
  196. }
  197. // Notify the extensions after deserialization
  198. message.SetStage (SoapMessageStage.AfterDeserialize);
  199. SoapExtension.ExecuteProcessMessage (_extensionChainHighPrio, message, stream, false);
  200. SoapExtension.ExecuteProcessMessage (_extensionChainMedPrio, message, stream, false);
  201. SoapExtension.ExecuteProcessMessage (_extensionChainLowPrio, message, stream, false);
  202. return message;
  203. //}
  204. }
  205. string ReadActionFromRequestElement (Stream stream, Encoding encoding)
  206. {
  207. try
  208. {
  209. StreamReader reader = new StreamReader (stream, encoding, false);
  210. XmlTextReader xmlReader = new XmlTextReader (reader);
  211. xmlReader.MoveToContent ();
  212. xmlReader.ReadStartElement ("Envelope", WebServiceHelper.SoapEnvelopeNamespace);
  213. while (! (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Body" && xmlReader.NamespaceURI == WebServiceHelper.SoapEnvelopeNamespace))
  214. xmlReader.Skip ();
  215. xmlReader.ReadStartElement ("Body", WebServiceHelper.SoapEnvelopeNamespace);
  216. xmlReader.MoveToContent ();
  217. return xmlReader.LocalName;
  218. }
  219. catch (Exception ex)
  220. {
  221. string errmsg = "The root element for the request could not be determined. ";
  222. errmsg += "When RoutingStyle is set to RequestElement, SoapExtensions configured ";
  223. errmsg += "via an attribute on the method cannot modify the request stream before it is read. ";
  224. errmsg += "The extension must be configured via the SoapExtensionTypes element in web.config ";
  225. errmsg += "or the request must arrive at the server as clear text.";
  226. throw new SoapException (errmsg, SoapException.ServerFaultCode, ex);
  227. }
  228. }
  229. void SerializeResponse (HttpResponse response, SoapServerMessage message)
  230. {
  231. SoapMethodStubInfo methodInfo = message.MethodStubInfo;
  232. if ((message.ContentEncoding != null) && (message.ContentEncoding.Length > 0))
  233. response.AppendHeader("Content-Encoding", message.ContentEncoding);
  234. response.ContentType = "text/xml; charset=utf-8";
  235. if (message.Exception != null) response.StatusCode = 500;
  236. Stream responseStream = response.OutputStream;
  237. Stream outStream = responseStream;
  238. bool bufferResponse = (methodInfo == null || methodInfo.MethodAttribute.BufferResponse);
  239. response.BufferOutput = bufferResponse;
  240. try
  241. {
  242. // While serializing, process extensions in reverse order
  243. if (bufferResponse)
  244. {
  245. outStream = SoapExtension.ExecuteChainStream (_extensionChainHighPrio, outStream);
  246. outStream = SoapExtension.ExecuteChainStream (_extensionChainMedPrio, outStream);
  247. outStream = SoapExtension.ExecuteChainStream (_extensionChainLowPrio, outStream);
  248. message.SetStage (SoapMessageStage.BeforeSerialize);
  249. SoapExtension.ExecuteProcessMessage (_extensionChainLowPrio, message, outStream, true);
  250. SoapExtension.ExecuteProcessMessage (_extensionChainMedPrio, message, outStream, true);
  251. SoapExtension.ExecuteProcessMessage (_extensionChainHighPrio, message, outStream, true);
  252. }
  253. XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (outStream);
  254. #if NET_2_0
  255. bool soap12 = message.SoapVersion == SoapProtocolVersion.Soap12;
  256. #else
  257. bool soap12 = false;
  258. #endif
  259. if (message.Exception == null)
  260. WebServiceHelper.WriteSoapMessage (xtw, methodInfo, SoapHeaderDirection.Out, message.OutParameters, message.Headers, soap12);
  261. else if (methodInfo != null) {
  262. #if NET_2_0
  263. if (soap12)
  264. WebServiceHelper.WriteSoapMessage (xtw, methodInfo, SoapHeaderDirection.Fault, new Soap12Fault (message.Exception), message.Headers, soap12);
  265. else
  266. #endif
  267. {
  268. WebServiceHelper.WriteSoapMessage (xtw, methodInfo, SoapHeaderDirection.Fault, new Fault (message.Exception), message.Headers, soap12);
  269. }
  270. }
  271. else {
  272. #if NET_2_0
  273. if (soap12)
  274. WebServiceHelper.WriteSoapMessage (xtw, SoapBindingUse.Literal, Soap12Fault.Serializer, null, new Soap12Fault (message.Exception), null, soap12);
  275. else
  276. #endif
  277. {
  278. WebServiceHelper.WriteSoapMessage (xtw, SoapBindingUse.Literal, Fault.Serializer, null, new Fault (message.Exception), null, soap12);
  279. }
  280. }
  281. if (bufferResponse)
  282. {
  283. message.SetStage (SoapMessageStage.AfterSerialize);
  284. SoapExtension.ExecuteProcessMessage (_extensionChainLowPrio, message, outStream, true);
  285. SoapExtension.ExecuteProcessMessage (_extensionChainMedPrio, message, outStream, true);
  286. SoapExtension.ExecuteProcessMessage (_extensionChainHighPrio, message, outStream, true);
  287. }
  288. xtw.Flush ();
  289. }
  290. catch (Exception ex)
  291. {
  292. // If the response is buffered, we can discard the response and
  293. // serialize a new Fault message as response.
  294. if (bufferResponse) throw ex;
  295. // If it is not buffered, we can't rollback what has been sent,
  296. // so we can only close the connection and return.
  297. responseStream.Close ();
  298. return;
  299. }
  300. }
  301. void SerializeFault (HttpContext context, SoapServerMessage requestMessage, Exception ex)
  302. {
  303. SoapException soex = ex as SoapException;
  304. if (soex == null) soex = new SoapException (ex.Message, SoapException.ServerFaultCode, ex);
  305. SoapServerMessage faultMessage;
  306. if (requestMessage != null)
  307. faultMessage = new SoapServerMessage (context.Request, soex, requestMessage.MethodStubInfo, requestMessage.Server, requestMessage.Stream);
  308. else
  309. faultMessage = new SoapServerMessage (context.Request, soex, null, null, null);
  310. #if NET_2_0
  311. object soapVer = context.Items ["WebServiceSoapVersion"];
  312. if (soapVer != null)
  313. faultMessage.SetSoapVersion ((SoapProtocolVersion) soapVer);
  314. #endif
  315. SerializeResponse (context.Response, faultMessage);
  316. context.Response.End ();
  317. return;
  318. }
  319. private SoapServerMessage Invoke (HttpContext ctx, SoapServerMessage requestMessage)
  320. {
  321. SoapMethodStubInfo methodInfo = requestMessage.MethodStubInfo;
  322. // Assign header values to web service members
  323. requestMessage.UpdateHeaderValues (requestMessage.Server, methodInfo.Headers);
  324. // Fill an array with the input parameters at the right position
  325. object[] parameters = new object[methodInfo.MethodInfo.Parameters.Length];
  326. ParameterInfo[] inParams = methodInfo.MethodInfo.InParameters;
  327. for (int n=0; n<inParams.Length; n++)
  328. parameters [inParams[n].Position] = requestMessage.InParameters [n];
  329. // Invoke the method
  330. try
  331. {
  332. object[] results = methodInfo.MethodInfo.Invoke (requestMessage.Server, parameters);
  333. requestMessage.OutParameters = results;
  334. }
  335. catch (TargetInvocationException ex)
  336. {
  337. throw ex.InnerException;
  338. }
  339. // Check that headers with MustUnderstand flag have been understood
  340. foreach (SoapHeader header in requestMessage.Headers)
  341. {
  342. if (header.MustUnderstand && !header.DidUnderstand)
  343. throw new SoapHeaderException ("Header not understood: " + header.GetType(), SoapException.MustUnderstandFaultCode);
  344. }
  345. // Collect headers that must be sent to the client
  346. requestMessage.CollectHeaders (requestMessage.Server, methodInfo.Headers, SoapHeaderDirection.Out);
  347. return requestMessage;
  348. }
  349. }
  350. }