WebHttpBehavior.cs 12 KB

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