WebHttpBehavior.cs 12 KB

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