HttpSoapWebServiceHandler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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);
  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);
  77. }
  78. if (methodInfo != null && methodInfo.OneWay) {
  79. context.Response.BufferOutput = false;
  80. context.Response.StatusCode = 202;
  81. context.Response.Flush ();
  82. context.Response.Close ();
  83. Invoke (context, requestMessage);
  84. } else {
  85. responseMessage = Invoke (context, requestMessage);
  86. SerializeResponse (context.Response, responseMessage);
  87. }
  88. }
  89. catch (Exception ex)
  90. {
  91. if (methodInfo != null && methodInfo.OneWay) {
  92. context.Response.StatusCode = 500;
  93. context.Response.Flush ();
  94. context.Response.Close ();
  95. } else {
  96. SerializeFault (context, requestMessage, ex);
  97. }
  98. }
  99. finally {
  100. IDisposable disp = requestMessage.Server as IDisposable;
  101. requestMessage = null;
  102. if (disp != null)
  103. disp.Dispose();
  104. }
  105. }
  106. SoapServerMessage DeserializeRequest (HttpContext context)
  107. {
  108. HttpRequest request = context.Request;
  109. Stream stream = request.InputStream;
  110. //using (stream)
  111. //{
  112. string soapAction = null;
  113. string ctype;
  114. Encoding encoding = WebServiceHelper.GetContentEncoding (request.ContentType, out ctype);
  115. #if NET_2_0
  116. if (ctype != "text/xml" && ctype != "application/soap+xml")
  117. #else
  118. if (ctype != "text/xml")
  119. #endif
  120. throw new WebException ("Content is not XML: " + ctype);
  121. object server = CreateServerInstance ();
  122. SoapServerMessage message = new SoapServerMessage (request, server, stream);
  123. message.SetStage (SoapMessageStage.BeforeDeserialize);
  124. message.ContentType = ctype;
  125. #if NET_2_0
  126. object soapVer = context.Items ["WebServiceSoapVersion"];
  127. if (soapVer != null)
  128. message.SetSoapVersion ((SoapProtocolVersion) soapVer);
  129. #endif
  130. // If the routing style is SoapAction, then we can get the method information now
  131. // and set it to the SoapMessage
  132. if (_typeStubInfo.RoutingStyle == SoapServiceRoutingStyle.SoapAction && !message.IsSoap12)
  133. {
  134. soapAction = request.Headers ["SOAPAction"];
  135. if (soapAction == null) throw new SoapException ("Missing SOAPAction header", WebServiceHelper.ClientFaultCode (message.IsSoap12));
  136. methodInfo = _typeStubInfo.GetMethodForSoapAction (soapAction);
  137. if (methodInfo == null) throw new SoapException ("Server did not recognize the value of HTTP header SOAPAction: " + soapAction, WebServiceHelper.ClientFaultCode (message.IsSoap12));
  138. message.MethodStubInfo = methodInfo;
  139. }
  140. // Execute the high priority global extensions. Do not try to execute the medium and
  141. // low priority extensions because if the routing style is RequestElement we still
  142. // don't have method information
  143. _extensionChainHighPrio = SoapExtension.CreateExtensionChain (_typeStubInfo.SoapExtensions[0]);
  144. stream = SoapExtension.ExecuteChainStream (_extensionChainHighPrio, stream);
  145. SoapExtension.ExecuteProcessMessage (_extensionChainHighPrio, message, stream, false);
  146. // If the routing style is RequestElement, try to get the method name from the
  147. // stream processed by the high priority extensions
  148. if (_typeStubInfo.RoutingStyle == SoapServiceRoutingStyle.RequestElement || message.IsSoap12)
  149. {
  150. MemoryStream mstream;
  151. byte[] buffer = null;
  152. if (stream.CanSeek)
  153. {
  154. buffer = new byte [stream.Length];
  155. for (int n=0; n<stream.Length;)
  156. n += stream.Read (buffer, n, (int)stream.Length-n);
  157. mstream = new MemoryStream (buffer);
  158. }
  159. else
  160. {
  161. buffer = new byte [500];
  162. mstream = new MemoryStream ();
  163. int len;
  164. while ((len = stream.Read (buffer, 0, 500)) > 0)
  165. mstream.Write (buffer, 0, len);
  166. mstream.Position = 0;
  167. buffer = mstream.ToArray ();
  168. }
  169. soapAction = ReadActionFromRequestElement (new MemoryStream (buffer), encoding, message.IsSoap12);
  170. stream = mstream;
  171. methodInfo = (SoapMethodStubInfo) _typeStubInfo.GetMethod (soapAction);
  172. message.MethodStubInfo = methodInfo;
  173. }
  174. // Whatever routing style we used, we should now have the method information.
  175. // We can now notify the remaining extensions
  176. if (methodInfo == null) throw new SoapException ("Method '" + soapAction + "' not defined in the web service '" + _typeStubInfo.LogicalType.WebServiceName + "'", WebServiceHelper.ClientFaultCode (message.IsSoap12));
  177. _extensionChainMedPrio = SoapExtension.CreateExtensionChain (methodInfo.SoapExtensions);
  178. _extensionChainLowPrio = SoapExtension.CreateExtensionChain (_typeStubInfo.SoapExtensions[1]);
  179. stream = SoapExtension.ExecuteChainStream (_extensionChainMedPrio, stream);
  180. stream = SoapExtension.ExecuteChainStream (_extensionChainLowPrio, stream);
  181. SoapExtension.ExecuteProcessMessage (_extensionChainMedPrio, message, stream, false);
  182. SoapExtension.ExecuteProcessMessage (_extensionChainLowPrio, message, stream, false);
  183. // Deserialize the request
  184. StreamReader reader = new StreamReader (stream, encoding, false);
  185. XmlTextReader xmlReader = new XmlTextReader (reader);
  186. try
  187. {
  188. object content;
  189. SoapHeaderCollection headers;
  190. WebServiceHelper.ReadSoapMessage (xmlReader, methodInfo, SoapHeaderDirection.In, message.IsSoap12, out content, out headers);
  191. message.InParameters = (object []) content;
  192. message.SetHeaders (headers);
  193. }
  194. catch (Exception ex)
  195. {
  196. throw new SoapException ("Could not deserialize Soap message", WebServiceHelper.ClientFaultCode (message.IsSoap12), ex);
  197. }
  198. // Notify the extensions after deserialization
  199. message.SetStage (SoapMessageStage.AfterDeserialize);
  200. SoapExtension.ExecuteProcessMessage (_extensionChainHighPrio, message, stream, false);
  201. SoapExtension.ExecuteProcessMessage (_extensionChainMedPrio, message, stream, false);
  202. SoapExtension.ExecuteProcessMessage (_extensionChainLowPrio, message, stream, false);
  203. return message;
  204. //}
  205. }
  206. string ReadActionFromRequestElement (Stream stream, Encoding encoding, bool soap12)
  207. {
  208. string envNS = soap12 ?
  209. WebServiceHelper.Soap12EnvelopeNamespace :
  210. WebServiceHelper.SoapEnvelopeNamespace;
  211. try
  212. {
  213. StreamReader reader = new StreamReader (stream, encoding, false);
  214. XmlTextReader xmlReader = new XmlTextReader (reader);
  215. xmlReader.MoveToContent ();
  216. xmlReader.ReadStartElement ("Envelope", envNS);
  217. while (! (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Body" && xmlReader.NamespaceURI == envNS))
  218. xmlReader.Skip ();
  219. xmlReader.ReadStartElement ("Body", envNS);
  220. xmlReader.MoveToContent ();
  221. return xmlReader.LocalName;
  222. }
  223. catch (Exception ex)
  224. {
  225. string errmsg = "The root element for the request could not be determined. ";
  226. errmsg += "When RoutingStyle is set to RequestElement, SoapExtensions configured ";
  227. errmsg += "via an attribute on the method cannot modify the request stream before it is read. ";
  228. errmsg += "The extension must be configured via the SoapExtensionTypes element in web.config ";
  229. errmsg += "or the request must arrive at the server as clear text.";
  230. throw new SoapException (errmsg, WebServiceHelper.ServerFaultCode (soap12), ex);
  231. }
  232. }
  233. void SerializeResponse (HttpResponse response, SoapServerMessage message)
  234. {
  235. SoapMethodStubInfo methodInfo = message.MethodStubInfo;
  236. if ((message.ContentEncoding != null) && (message.ContentEncoding.Length > 0))
  237. response.AppendHeader("Content-Encoding", message.ContentEncoding);
  238. response.ContentType = message.IsSoap12 ?
  239. "application/soap+xml; charset=utf-8" :
  240. "text/xml; charset=utf-8";
  241. if (message.Exception != null) response.StatusCode = 500;
  242. Stream responseStream = response.OutputStream;
  243. Stream outStream = responseStream;
  244. bool bufferResponse = (methodInfo == null || methodInfo.MethodAttribute.BufferResponse);
  245. response.BufferOutput = bufferResponse;
  246. try
  247. {
  248. // While serializing, process extensions in reverse order
  249. if (bufferResponse)
  250. {
  251. outStream = SoapExtension.ExecuteChainStream (_extensionChainHighPrio, outStream);
  252. outStream = SoapExtension.ExecuteChainStream (_extensionChainMedPrio, outStream);
  253. outStream = SoapExtension.ExecuteChainStream (_extensionChainLowPrio, outStream);
  254. message.SetStage (SoapMessageStage.BeforeSerialize);
  255. SoapExtension.ExecuteProcessMessage (_extensionChainLowPrio, message, outStream, true);
  256. SoapExtension.ExecuteProcessMessage (_extensionChainMedPrio, message, outStream, true);
  257. SoapExtension.ExecuteProcessMessage (_extensionChainHighPrio, message, outStream, true);
  258. }
  259. XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (outStream);
  260. if (message.Exception == null)
  261. WebServiceHelper.WriteSoapMessage (xtw, methodInfo, SoapHeaderDirection.Out, message.OutParameters, message.Headers, message.IsSoap12);
  262. else if (methodInfo != null) {
  263. #if NET_2_0
  264. if (message.IsSoap12)
  265. WebServiceHelper.WriteSoapMessage (xtw, methodInfo, SoapHeaderDirection.Fault, new Soap12Fault (message.Exception), message.Headers, message.IsSoap12);
  266. else
  267. #endif
  268. {
  269. WebServiceHelper.WriteSoapMessage (xtw, methodInfo, SoapHeaderDirection.Fault, new Fault (message.Exception), message.Headers, message.IsSoap12);
  270. }
  271. }
  272. else {
  273. #if NET_2_0
  274. if (message.IsSoap12)
  275. WebServiceHelper.WriteSoapMessage (xtw, SoapBindingUse.Literal, Soap12Fault.Serializer, null, new Soap12Fault (message.Exception), null, message.IsSoap12);
  276. else
  277. #endif
  278. {
  279. WebServiceHelper.WriteSoapMessage (xtw, SoapBindingUse.Literal, Fault.Serializer, null, new Fault (message.Exception), null, message.IsSoap12);
  280. }
  281. }
  282. if (bufferResponse)
  283. {
  284. message.SetStage (SoapMessageStage.AfterSerialize);
  285. SoapExtension.ExecuteProcessMessage (_extensionChainLowPrio, message, outStream, true);
  286. SoapExtension.ExecuteProcessMessage (_extensionChainMedPrio, message, outStream, true);
  287. SoapExtension.ExecuteProcessMessage (_extensionChainHighPrio, message, outStream, true);
  288. }
  289. xtw.Flush ();
  290. }
  291. catch (Exception ex)
  292. {
  293. // If the response is buffered, we can discard the response and
  294. // serialize a new Fault message as response.
  295. if (bufferResponse) throw ex;
  296. // If it is not buffered, we can't rollback what has been sent,
  297. // so we can only close the connection and return.
  298. responseStream.Close ();
  299. return;
  300. }
  301. }
  302. void SerializeFault (HttpContext context, SoapServerMessage requestMessage, Exception ex)
  303. {
  304. SoapException soex = ex as SoapException;
  305. if (soex == null) soex = new SoapException (ex.Message, WebServiceHelper.ServerFaultCode (requestMessage != null && requestMessage.IsSoap12), ex);
  306. SoapServerMessage faultMessage;
  307. if (requestMessage != null)
  308. faultMessage = new SoapServerMessage (context.Request, soex, requestMessage.MethodStubInfo, requestMessage.Server, requestMessage.Stream);
  309. else
  310. faultMessage = new SoapServerMessage (context.Request, soex, null, null, null);
  311. #if NET_2_0
  312. object soapVer = context.Items ["WebServiceSoapVersion"];
  313. if (soapVer != null)
  314. faultMessage.SetSoapVersion ((SoapProtocolVersion) soapVer);
  315. #endif
  316. SerializeResponse (context.Response, faultMessage);
  317. context.Response.End ();
  318. return;
  319. }
  320. private SoapServerMessage Invoke (HttpContext ctx, SoapServerMessage requestMessage)
  321. {
  322. SoapMethodStubInfo methodInfo = requestMessage.MethodStubInfo;
  323. // Assign header values to web service members
  324. requestMessage.UpdateHeaderValues (requestMessage.Server, methodInfo.Headers);
  325. // Fill an array with the input parameters at the right position
  326. object[] parameters = new object[methodInfo.MethodInfo.Parameters.Length];
  327. ParameterInfo[] inParams = methodInfo.MethodInfo.InParameters;
  328. for (int n=0; n<inParams.Length; n++)
  329. parameters [inParams[n].Position] = requestMessage.InParameters [n];
  330. // Invoke the method
  331. try
  332. {
  333. object[] results = methodInfo.MethodInfo.Invoke (requestMessage.Server, parameters);
  334. requestMessage.OutParameters = results;
  335. }
  336. catch (TargetInvocationException ex)
  337. {
  338. throw ex.InnerException;
  339. }
  340. // Check that headers with MustUnderstand flag have been understood
  341. foreach (SoapHeader header in requestMessage.Headers)
  342. {
  343. if (header.MustUnderstand && !header.DidUnderstand)
  344. throw new SoapHeaderException ("Header not understood: " + header.GetType(), WebServiceHelper.MustUnderstandFaultCode (requestMessage.IsSoap12));
  345. }
  346. // Collect headers that must be sent to the client
  347. requestMessage.CollectHeaders (requestMessage.Server, methodInfo.Headers, SoapHeaderDirection.Out);
  348. return requestMessage;
  349. }
  350. }
  351. }