WebHttpBehavior.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. WebAttributeInfo info = null;
  42. var wg = ob as WebGetAttribute;
  43. if (wg != null)
  44. return wg.Info;
  45. var wi = ob as WebInvokeAttribute;
  46. if (wi != null)
  47. return wi.Info;
  48. }
  49. return new WebGetAttribute ().Info; // blank one
  50. }
  51. }
  52. public class WebHttpBehavior : IEndpointBehavior
  53. {
  54. public WebHttpBehavior ()
  55. {
  56. DefaultBodyStyle = WebMessageBodyStyle.Bare;
  57. DefaultOutgoingRequestFormat = WebMessageFormat.Xml;
  58. DefaultOutgoingResponseFormat = WebMessageFormat.Xml;
  59. }
  60. #if NET_4_0
  61. public virtual bool AutomaticFormatSelectionEnabled { get; set; }
  62. public virtual bool FaultExceptionEnabled { get; set; }
  63. public virtual bool HelpEnabled { get; set; }
  64. #endif
  65. public virtual WebMessageBodyStyle DefaultBodyStyle { get; set; }
  66. public virtual WebMessageFormat DefaultOutgoingRequestFormat { get; set; }
  67. public virtual WebMessageFormat DefaultOutgoingResponseFormat { get; set; }
  68. public virtual void AddBindingParameters (ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
  69. {
  70. // nothing
  71. }
  72. [MonoTODO]
  73. protected virtual void AddClientErrorInspector (ServiceEndpoint endpoint, ClientRuntime clientRuntime)
  74. {
  75. // clientRuntime.MessageInspectors.Add (something);
  76. }
  77. #if !NET_2_1
  78. protected virtual void AddServerErrorHandlers (ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
  79. {
  80. endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add (new WebHttpErrorHandler ());
  81. }
  82. #endif
  83. public virtual void ApplyClientBehavior (ServiceEndpoint endpoint, ClientRuntime clientRuntime)
  84. {
  85. AddClientErrorInspector (endpoint, clientRuntime);
  86. foreach (ClientOperation oper in clientRuntime.Operations) {
  87. var req = GetRequestClientFormatter (endpoint.Contract.Operations.Find (oper.Name), endpoint);
  88. var res = GetReplyClientFormatter (endpoint.Contract.Operations.Find (oper.Name), endpoint);
  89. oper.Formatter = new ClientPairFormatter (req, res);
  90. }
  91. }
  92. public virtual void ApplyDispatchBehavior (ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
  93. {
  94. #if NET_2_1
  95. throw new NotImplementedException ();
  96. #else
  97. endpointDispatcher.DispatchRuntime.OperationSelector = GetOperationSelector (endpoint);
  98. // FIXME: get HostNameComparisonMode from WebHttpBinding by some means.
  99. endpointDispatcher.FilterPriority = 1; // It is to take higher priority than that of ServiceMetadataExtension (whose URL likely conflicts with this one).
  100. endpointDispatcher.AddressFilter = new PrefixEndpointAddressMessageFilter (endpoint.Address);
  101. endpointDispatcher.ContractFilter = new MatchAllMessageFilter ();
  102. AddServerErrorHandlers (endpoint, endpointDispatcher);
  103. foreach (DispatchOperation oper in endpointDispatcher.DispatchRuntime.Operations) {
  104. var req = GetRequestDispatchFormatter (endpoint.Contract.Operations.Find (oper.Name), endpoint);
  105. var res = GetReplyDispatchFormatter (endpoint.Contract.Operations.Find (oper.Name), endpoint);
  106. oper.Formatter = new DispatchPairFormatter (req, res);
  107. }
  108. endpointDispatcher.DispatchRuntime.UnhandledDispatchOperation = new DispatchOperation (endpointDispatcher.DispatchRuntime, "*", "*", "*") {
  109. Invoker = new EndpointNotFoundOperationInvoker (),
  110. DeserializeRequest = false,
  111. SerializeReply = false};
  112. #endif
  113. }
  114. internal class ClientPairFormatter : IClientMessageFormatter
  115. {
  116. public ClientPairFormatter (IClientMessageFormatter request, IClientMessageFormatter reply)
  117. {
  118. this.request = request;
  119. this.reply = reply;
  120. }
  121. IClientMessageFormatter request, reply;
  122. public Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
  123. {
  124. return request.SerializeRequest (messageVersion, parameters);
  125. }
  126. public object DeserializeReply (Message message, object [] parameters)
  127. {
  128. return reply.DeserializeReply (message, parameters);
  129. }
  130. }
  131. #if !NET_2_1
  132. internal class DispatchPairFormatter : IDispatchMessageFormatter
  133. {
  134. public DispatchPairFormatter (IDispatchMessageFormatter request, IDispatchMessageFormatter reply)
  135. {
  136. this.request = request;
  137. this.reply = reply;
  138. }
  139. IDispatchMessageFormatter request;
  140. IDispatchMessageFormatter reply;
  141. public void DeserializeRequest (Message message, object [] parameters)
  142. {
  143. request.DeserializeRequest (message, parameters);
  144. }
  145. public Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
  146. {
  147. return reply.SerializeReply (messageVersion, parameters, result);
  148. }
  149. }
  150. protected virtual WebHttpDispatchOperationSelector GetOperationSelector (ServiceEndpoint endpoint)
  151. {
  152. return new WebHttpDispatchOperationSelector (endpoint);
  153. }
  154. #endif
  155. protected virtual QueryStringConverter GetQueryStringConverter (OperationDescription operationDescription)
  156. {
  157. return new QueryStringConverter ();
  158. }
  159. protected virtual IClientMessageFormatter GetReplyClientFormatter (OperationDescription operationDescription, ServiceEndpoint endpoint)
  160. {
  161. return new WebMessageFormatter.ReplyClientFormatter (operationDescription, endpoint, GetQueryStringConverter (operationDescription), this);
  162. }
  163. #if !NET_2_1
  164. protected virtual IDispatchMessageFormatter GetReplyDispatchFormatter (OperationDescription operationDescription, ServiceEndpoint endpoint)
  165. {
  166. return new WebMessageFormatter.ReplyDispatchFormatter (operationDescription, endpoint, GetQueryStringConverter (operationDescription), this);
  167. }
  168. #endif
  169. protected virtual IClientMessageFormatter GetRequestClientFormatter (OperationDescription operationDescription, ServiceEndpoint endpoint)
  170. {
  171. return new WebMessageFormatter.RequestClientFormatter (operationDescription, endpoint, GetQueryStringConverter (operationDescription), this);
  172. }
  173. #if !NET_2_1
  174. protected virtual IDispatchMessageFormatter GetRequestDispatchFormatter (OperationDescription operationDescription, ServiceEndpoint endpoint)
  175. {
  176. return new WebMessageFormatter.RequestDispatchFormatter (operationDescription, endpoint, GetQueryStringConverter (operationDescription), this);
  177. }
  178. #endif
  179. WebMessageBodyStyle GetBodyStyle (WebAttributeInfo wai)
  180. {
  181. return wai != null && wai.IsBodyStyleSetExplicitly ? wai.BodyStyle : DefaultBodyStyle;
  182. }
  183. protected void ValidateOperation (OperationDescription operation)
  184. {
  185. var wai = operation.GetWebAttributeInfo ();
  186. if (wai.Method == "GET")
  187. return;
  188. var style = GetBodyStyle (wai);
  189. // if the style is wrapped there won't be problems
  190. if (style == WebMessageBodyStyle.Wrapped)
  191. return;
  192. string [] parameters;
  193. if (wai.UriTemplate != null) {
  194. // find all variables in the URI
  195. var uri = new UriTemplate (wai.UriTemplate);
  196. parameters = new string [uri.PathSegmentVariableNames.Count + uri.QueryValueVariableNames.Count];
  197. uri.PathSegmentVariableNames.CopyTo (parameters, 0);
  198. uri.QueryValueVariableNames.CopyTo (parameters, uri.PathSegmentVariableNames.Count);
  199. // sort because Array.BinarySearch is the easiest way for case-insensitive search
  200. Array.Sort (parameters, StringComparer.InvariantCultureIgnoreCase);
  201. } else
  202. parameters = new string [0];
  203. bool hasBody = false;
  204. foreach (var msg in operation.Messages) {
  205. if (msg.Direction == MessageDirection.Input) {
  206. // the message is for a request
  207. // if requests are wrapped there is nothing to check
  208. if (style == WebMessageBodyStyle.WrappedRequest)
  209. continue;
  210. foreach (var part in msg.Body.Parts) {
  211. if (Array.BinarySearch (parameters, part.Name, StringComparer.InvariantCultureIgnoreCase) < 0) {
  212. // this part of the message is not covered by a variable in the URI
  213. // so it must be passed in the body
  214. if (hasBody)
  215. 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));
  216. hasBody = true;
  217. }
  218. }
  219. } else {
  220. // the message is for a response
  221. if (style != WebMessageBodyStyle.WrappedResponse && msg.Body.Parts.Count > 0)
  222. throw new InvalidOperationException (String.Format ("Operation '{0}' has output parameters. BodyStyle must be 'Wrapped' or 'WrappedResponse' on the operation WebInvoke/WebGet attribute.", operation.Name));
  223. }
  224. }
  225. }
  226. [MonoTODO ("check UriTemplate validity")]
  227. public virtual void Validate (ServiceEndpoint endpoint)
  228. {
  229. if (endpoint == null)
  230. throw new ArgumentNullException ("endpoint");
  231. foreach (var oper in endpoint.Contract.Operations) {
  232. ValidateOperation (oper);
  233. }
  234. ValidateBinding (endpoint);
  235. }
  236. protected virtual void ValidateBinding (ServiceEndpoint endpoint)
  237. {
  238. switch (endpoint.Binding.Scheme) {
  239. case "http":
  240. case "https":
  241. break;
  242. default:
  243. throw new InvalidOperationException ("Only http and https are allowed for WebHttpBehavior");
  244. }
  245. if (!endpoint.Binding.MessageVersion.Equals (MessageVersion.None))
  246. throw new InvalidOperationException ("Only MessageVersion.None is allowed for WebHttpBehavior");
  247. if (!endpoint.Binding.CreateBindingElements ().Find<TransportBindingElement> ().ManualAddressing)
  248. throw new InvalidOperationException ("ManualAddressing in the transport binding element in the binding must be true for WebHttpBehavior");
  249. }
  250. #if !NET_2_1
  251. internal class WebHttpErrorHandler : IErrorHandler
  252. {
  253. public void ProvideFault (Exception error, MessageVersion version, ref Message fault)
  254. {
  255. if (!(error is EndpointNotFoundException))
  256. return;
  257. fault = Message.CreateMessage (version, null);
  258. var prop = new HttpResponseMessageProperty ();
  259. prop.StatusCode = HttpStatusCode.NotFound;
  260. fault.Properties.Add (HttpResponseMessageProperty.Name, prop);
  261. }
  262. public bool HandleError (Exception error)
  263. {
  264. return false;
  265. }
  266. }
  267. class EndpointNotFoundOperationInvoker : IOperationInvoker
  268. {
  269. public bool IsSynchronous {
  270. get { return true; }
  271. }
  272. public object [] AllocateInputs ()
  273. {
  274. return new object [1];
  275. }
  276. public object Invoke (object instance, object [] inputs, out object [] outputs)
  277. {
  278. throw new EndpointNotFoundException ();
  279. }
  280. public IAsyncResult InvokeBegin (object instance, object [] inputs, AsyncCallback callback, object state)
  281. {
  282. throw new EndpointNotFoundException ();
  283. }
  284. public object InvokeEnd (object instance, out object [] outputs, IAsyncResult result)
  285. {
  286. throw new InvalidOperationException ();
  287. }
  288. }
  289. #endif
  290. }
  291. }