HttpSoapWebServiceHandler.cs 13 KB

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