WebHttpBehavior.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //
  2. // WebHttpBehavior.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Net;
  30. using System.ServiceModel;
  31. using System.ServiceModel.Channels;
  32. using System.ServiceModel.Dispatcher;
  33. using System.ServiceModel.Web;
  34. namespace System.ServiceModel.Description
  35. {
  36. internal static class WebHttpBehaviorExtensions
  37. {
  38. public static WebAttributeInfo GetWebAttributeInfo (this OperationDescription od)
  39. {
  40. foreach (IOperationBehavior ob in od.Behaviors) {
  41. var wg = ob as WebGetAttribute;
  42. if (wg != null)
  43. return wg.Info;
  44. var wi = ob as WebInvokeAttribute;
  45. if (wi != null)
  46. return wi.Info;
  47. }
  48. return new WebGetAttribute ().Info; // blank one
  49. }
  50. }
  51. public class WebHttpBehavior : IEndpointBehavior
  52. {
  53. public WebHttpBehavior ()
  54. {
  55. DefaultBodyStyle = WebMessageBodyStyle.Bare;
  56. DefaultOutgoingRequestFormat = WebMessageFormat.Xml;
  57. DefaultOutgoingResponseFormat = WebMessageFormat.Xml;
  58. }
  59. public virtual bool AutomaticFormatSelectionEnabled { get; set; }
  60. public virtual bool FaultExceptionEnabled { get; set; }
  61. public virtual bool HelpEnabled { get; set; }
  62. public virtual WebMessageBodyStyle DefaultBodyStyle { get; set; }
  63. public virtual WebMessageFormat DefaultOutgoingRequestFormat { get; set; }
  64. public virtual WebMessageFormat DefaultOutgoingResponseFormat { get; set; }
  65. public virtual void AddBindingParameters (ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
  66. {
  67. // nothing
  68. }
  69. [MonoTODO]
  70. protected virtual void AddClientErrorInspector (ServiceEndpoint endpoint, ClientRuntime clientRuntime)
  71. {
  72. // clientRuntime.MessageInspectors.Add (something);
  73. }
  74. #if !MOBILE && !XAMMAC_4_5
  75. protected virtual void AddServerErrorHandlers (ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
  76. {
  77. endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add (new WebHttpErrorHandler ());
  78. }
  79. #endif
  80. public virtual void ApplyClientBehavior (ServiceEndpoint endpoint, ClientRuntime clientRuntime)
  81. {
  82. AddClientErrorInspector (endpoint, clientRuntime);
  83. foreach (ClientOperation oper in clientRuntime.Operations) {
  84. var req = GetRequestClientFormatter (endpoint.Contract.Operations.Find (oper.Name), endpoint);
  85. var res = GetReplyClientFormatter (endpoint.Contract.Operations.Find (oper.Name), endpoint);
  86. oper.Formatter = new ClientPairFormatter (req, res);
  87. }
  88. }
  89. public virtual void ApplyDispatchBehavior (ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
  90. {
  91. #if MOBILE || XAMMAC_4_5
  92. throw new NotImplementedException ();
  93. #else
  94. endpointDispatcher.DispatchRuntime.OperationSelector = GetOperationSelector (endpoint);
  95. // FIXME: get HostNameComparisonMode from WebHttpBinding by some means.
  96. endpointDispatcher.FilterPriority = 1; // It is to take higher priority than that of ServiceMetadataExtension (whose URL likely conflicts with this one).
  97. endpointDispatcher.AddressFilter = new PrefixEndpointAddressMessageFilter (endpoint.Address);
  98. endpointDispatcher.ContractFilter = new MatchAllMessageFilter ();
  99. AddServerErrorHandlers (endpoint, endpointDispatcher);
  100. foreach (DispatchOperation oper in endpointDispatcher.DispatchRuntime.Operations) {
  101. var req = GetRequestDispatchFormatter (endpoint.Contract.Operations.Find (oper.Name), endpoint);
  102. var res = GetReplyDispatchFormatter (endpoint.Contract.Operations.Find (oper.Name), endpoint);
  103. oper.Formatter = new DispatchPairFormatter (req, res);
  104. }
  105. endpointDispatcher.DispatchRuntime.UnhandledDispatchOperation = new DispatchOperation (endpointDispatcher.DispatchRuntime, "*", "*", "*") {
  106. Invoker = new EndpointNotFoundOperationInvoker (),
  107. DeserializeRequest = false,
  108. SerializeReply = false};
  109. #endif
  110. }
  111. internal class ClientPairFormatter : IClientMessageFormatter
  112. {
  113. public ClientPairFormatter (IClientMessageFormatter request, IClientMessageFormatter reply)
  114. {
  115. this.request = request;
  116. this.reply = reply;
  117. }
  118. IClientMessageFormatter request, reply;
  119. public Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
  120. {
  121. return request.SerializeRequest (messageVersion, parameters);
  122. }
  123. public object DeserializeReply (Message message, object [] parameters)
  124. {
  125. return reply.DeserializeReply (message, parameters);
  126. }
  127. }
  128. #if !MOBILE && !XAMMAC_4_5
  129. internal class DispatchPairFormatter : IDispatchMessageFormatter
  130. {
  131. public DispatchPairFormatter (IDispatchMessageFormatter request, IDispatchMessageFormatter reply)
  132. {
  133. this.request = request;
  134. this.reply = reply;
  135. }
  136. IDispatchMessageFormatter request;
  137. IDispatchMessageFormatter reply;
  138. public void DeserializeRequest (Message message, object [] parameters)
  139. {
  140. request.DeserializeRequest (message, parameters);
  141. }
  142. public Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
  143. {
  144. return reply.SerializeReply (messageVersion, parameters, result);
  145. }
  146. }
  147. protected virtual WebHttpDispatchOperationSelector GetOperationSelector (ServiceEndpoint endpoint)
  148. {
  149. return new WebHttpDispatchOperationSelector (endpoint);
  150. }
  151. #endif
  152. protected virtual QueryStringConverter GetQueryStringConverter (OperationDescription operationDescription)
  153. {
  154. return new QueryStringConverter ();
  155. }
  156. protected virtual IClientMessageFormatter GetReplyClientFormatter (OperationDescription operationDescription, ServiceEndpoint endpoint)
  157. {
  158. return new WebMessageFormatter.ReplyClientFormatter (operationDescription, endpoint, GetQueryStringConverter (operationDescription), this);
  159. }
  160. #if !MOBILE
  161. protected virtual IDispatchMessageFormatter GetReplyDispatchFormatter (OperationDescription operationDescription, ServiceEndpoint endpoint)
  162. {
  163. return new WebMessageFormatter.ReplyDispatchFormatter (operationDescription, endpoint, GetQueryStringConverter (operationDescription), this);
  164. }
  165. #endif
  166. protected virtual IClientMessageFormatter GetRequestClientFormatter (OperationDescription operationDescription, ServiceEndpoint endpoint)
  167. {
  168. return new WebMessageFormatter.RequestClientFormatter (operationDescription, endpoint, GetQueryStringConverter (operationDescription), this);
  169. }
  170. #if !MOBILE
  171. protected virtual IDispatchMessageFormatter GetRequestDispatchFormatter (OperationDescription operationDescription, ServiceEndpoint endpoint)
  172. {
  173. return new WebMessageFormatter.RequestDispatchFormatter (operationDescription, endpoint, GetQueryStringConverter (operationDescription), this);
  174. }
  175. #endif
  176. WebMessageBodyStyle GetBodyStyle (WebAttributeInfo wai)
  177. {
  178. return wai != null && wai.IsBodyStyleSetExplicitly ? wai.BodyStyle : DefaultBodyStyle;
  179. }
  180. protected void ValidateOperation (OperationDescription operation)
  181. {
  182. var wai = operation.GetWebAttributeInfo ();
  183. if (wai.Method == "GET")
  184. return;
  185. var style = GetBodyStyle (wai);
  186. // if the style is wrapped there won't be problems
  187. if (style == WebMessageBodyStyle.Wrapped)
  188. return;
  189. string [] parameters;
  190. if (wai.UriTemplate != null) {
  191. // find all variables in the URI
  192. var uri = new UriTemplate (wai.UriTemplate);
  193. parameters = new string [uri.PathSegmentVariableNames.Count + uri.QueryValueVariableNames.Count];
  194. uri.PathSegmentVariableNames.CopyTo (parameters, 0);
  195. uri.QueryValueVariableNames.CopyTo (parameters, uri.PathSegmentVariableNames.Count);
  196. // sort because Array.BinarySearch is the easiest way for case-insensitive search
  197. Array.Sort (parameters, StringComparer.InvariantCultureIgnoreCase);
  198. } else
  199. parameters = new string [0];
  200. bool hasBody = false;
  201. foreach (var msg in operation.Messages) {
  202. if (msg.Direction == MessageDirection.Input) {
  203. // the message is for a request
  204. // if requests are wrapped there is nothing to check
  205. if (style == WebMessageBodyStyle.WrappedRequest)
  206. continue;
  207. foreach (var part in msg.Body.Parts) {
  208. if (Array.BinarySearch (parameters, part.Name, StringComparer.InvariantCultureIgnoreCase) < 0) {
  209. // this part of the message is not covered by a variable in the URI
  210. // so it must be passed in the body
  211. if (hasBody)
  212. throw new InvalidOperationException (String.Format ("Operation '{0}' has multiple message body parts. Add parameters to the UriTemplate or change the BodyStyle to 'Wrapped' or 'WrappedRequest' on the WebInvoke/WebGet attribute.", operation.Name));
  213. hasBody = true;
  214. }
  215. }
  216. } else {
  217. // the message is for a response
  218. if (style != WebMessageBodyStyle.WrappedResponse && msg.Body.Parts.Count > 0)
  219. throw new InvalidOperationException (String.Format ("Operation '{0}' has output parameters. BodyStyle must be 'Wrapped' or 'WrappedResponse' on the operation WebInvoke/WebGet attribute.", operation.Name));
  220. }
  221. }
  222. }
  223. [MonoTODO ("check UriTemplate validity")]
  224. public virtual void Validate (ServiceEndpoint endpoint)
  225. {
  226. if (endpoint == null)
  227. throw new ArgumentNullException ("endpoint");
  228. foreach (var oper in endpoint.Contract.Operations) {
  229. ValidateOperation (oper);
  230. }
  231. ValidateBinding (endpoint);
  232. }
  233. protected virtual void ValidateBinding (ServiceEndpoint endpoint)
  234. {
  235. switch (endpoint.Binding.Scheme) {
  236. case "http":
  237. case "https":
  238. break;
  239. default:
  240. throw new InvalidOperationException ("Only http and https are allowed for WebHttpBehavior");
  241. }
  242. if (!endpoint.Binding.MessageVersion.Equals (MessageVersion.None))
  243. throw new InvalidOperationException ("Only MessageVersion.None is allowed for WebHttpBehavior");
  244. if (!endpoint.Binding.CreateBindingElements ().Find<TransportBindingElement> ().ManualAddressing)
  245. throw new InvalidOperationException ("ManualAddressing in the transport binding element in the binding must be true for WebHttpBehavior");
  246. }
  247. #if !MOBILE
  248. internal class WebHttpErrorHandler : IErrorHandler
  249. {
  250. public void ProvideFault (Exception error, MessageVersion version, ref Message fault)
  251. {
  252. if (!(error is EndpointNotFoundException))
  253. return;
  254. fault = Message.CreateMessage (version, null);
  255. var prop = new HttpResponseMessageProperty ();
  256. prop.StatusCode = HttpStatusCode.NotFound;
  257. fault.Properties.Add (HttpResponseMessageProperty.Name, prop);
  258. }
  259. public bool HandleError (Exception error)
  260. {
  261. return false;
  262. }
  263. }
  264. class EndpointNotFoundOperationInvoker : IOperationInvoker
  265. {
  266. public bool IsSynchronous {
  267. get { return true; }
  268. }
  269. public object [] AllocateInputs ()
  270. {
  271. return new object [1];
  272. }
  273. public object Invoke (object instance, object [] inputs, out object [] outputs)
  274. {
  275. throw new EndpointNotFoundException ();
  276. }
  277. public IAsyncResult InvokeBegin (object instance, object [] inputs, AsyncCallback callback, object state)
  278. {
  279. throw new EndpointNotFoundException ();
  280. }
  281. public object InvokeEnd (object instance, out object [] outputs, IAsyncResult result)
  282. {
  283. throw new InvalidOperationException ();
  284. }
  285. }
  286. #endif
  287. }
  288. }