2
0

WebMessageFormatter.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //
  2. // WebMessageFormatter.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.Collections.Specialized;
  30. using System.Reflection;
  31. using System.Runtime.Serialization;
  32. using System.Runtime.Serialization.Json;
  33. using System.ServiceModel;
  34. using System.ServiceModel.Channels;
  35. using System.ServiceModel.Dispatcher;
  36. using System.ServiceModel.Web;
  37. using System.Text;
  38. namespace System.ServiceModel.Description
  39. {
  40. internal abstract class WebMessageFormatter
  41. {
  42. OperationDescription operation;
  43. ServiceEndpoint endpoint;
  44. QueryStringConverter converter;
  45. WebHttpBehavior behavior;
  46. UriTemplate template;
  47. WebAttributeInfo info = null;
  48. public WebMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  49. {
  50. this.operation = operation;
  51. this.endpoint = endpoint;
  52. this.converter = converter;
  53. this.behavior = behavior;
  54. ApplyWebAttribute ();
  55. }
  56. void ApplyWebAttribute ()
  57. {
  58. MethodInfo mi = operation.SyncMethod ?? operation.BeginMethod;
  59. object [] atts = mi.GetCustomAttributes (typeof (WebGetAttribute), false);
  60. if (atts.Length > 0)
  61. info = ((WebGetAttribute) atts [0]).Info;
  62. atts = mi.GetCustomAttributes (typeof (WebInvokeAttribute), false);
  63. if (atts.Length > 0)
  64. info = ((WebInvokeAttribute) atts [0]).Info;
  65. if (info == null)
  66. info = new WebAttributeInfo ();
  67. template = info.BuildUriTemplate (Operation, GetMessageDescription (MessageDirection.Input));
  68. }
  69. public WebHttpBehavior Behavior {
  70. get { return behavior; }
  71. }
  72. public WebAttributeInfo Info {
  73. get { return info; }
  74. }
  75. public OperationDescription Operation {
  76. get { return operation; }
  77. }
  78. public QueryStringConverter Converter {
  79. get { return converter; }
  80. }
  81. public ServiceEndpoint Endpoint {
  82. get { return endpoint; }
  83. }
  84. public UriTemplate UriTemplate {
  85. get { return template; }
  86. }
  87. protected WebContentFormat ToContentFormat (WebMessageFormat src)
  88. {
  89. switch (src) {
  90. case WebMessageFormat.Xml:
  91. return WebContentFormat.Xml;
  92. case WebMessageFormat.Json:
  93. return WebContentFormat.Json;
  94. }
  95. throw new SystemException ("INTERNAL ERROR: should not happen");
  96. }
  97. protected void CheckMessageVersion (MessageVersion messageVersion)
  98. {
  99. if (messageVersion == null)
  100. throw new ArgumentNullException ("messageVersion");
  101. if (!MessageVersion.None.Equals (messageVersion))
  102. throw new ArgumentException ("Only MessageVersion.None is supported");
  103. }
  104. protected MessageDescription GetMessageDescription (MessageDirection dir)
  105. {
  106. foreach (MessageDescription md in operation.Messages)
  107. if (md.Direction == dir)
  108. return md;
  109. throw new SystemException ("INTERNAL ERROR: no corresponding message description for the specified direction: " + dir);
  110. }
  111. internal class RequestClientFormatter : WebClientMessageFormatter
  112. {
  113. public RequestClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  114. : base (operation, endpoint, converter, behavior)
  115. {
  116. }
  117. }
  118. internal class ReplyClientFormatter : WebClientMessageFormatter
  119. {
  120. public ReplyClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  121. : base (operation, endpoint, converter, behavior)
  122. {
  123. }
  124. }
  125. internal class RequestDispatchFormatter : WebDispatchMessageFormatter
  126. {
  127. public RequestDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  128. : base (operation, endpoint, converter, behavior)
  129. {
  130. }
  131. }
  132. internal class ReplyDispatchFormatter : WebDispatchMessageFormatter
  133. {
  134. public ReplyDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  135. : base (operation, endpoint, converter, behavior)
  136. {
  137. }
  138. }
  139. internal abstract class WebClientMessageFormatter : WebMessageFormatter, IClientMessageFormatter
  140. {
  141. protected WebClientMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  142. : base (operation, endpoint, converter, behavior)
  143. {
  144. }
  145. public Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
  146. {
  147. if (parameters == null)
  148. throw new ArgumentNullException ("parameters");
  149. CheckMessageVersion (messageVersion);
  150. var c = new NameValueCollection ();
  151. MessageDescription md = GetMessageDescription (MessageDirection.Input);
  152. if (parameters.Length != md.Body.Parts.Count)
  153. throw new ArgumentException ("Parameter array length does not match the number of message body parts");
  154. for (int i = 0; i < parameters.Length; i++) {
  155. var p = md.Body.Parts [i];
  156. string name = p.Name.ToUpperInvariant ();
  157. if (UriTemplate.PathSegmentVariableNames.Contains (name) ||
  158. UriTemplate.QueryValueVariableNames.Contains (name))
  159. c.Add (name, parameters [i] != null ? Converter.ConvertValueToString (parameters [i], parameters [i].GetType ()) : null);
  160. else
  161. // FIXME: bind as a message part
  162. throw new NotImplementedException (String.Format ("parameter {0} is not contained in the URI template {1} {2} {3}", p.Name, UriTemplate, UriTemplate.PathSegmentVariableNames.Count, UriTemplate.QueryValueVariableNames.Count));
  163. }
  164. Uri to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
  165. Message ret = Message.CreateMessage (messageVersion, (string) null);
  166. ret.Headers.To = to;
  167. var hp = new HttpRequestMessageProperty ();
  168. hp.Method = Info.Method;
  169. // FIXME: isn't it always null?
  170. if (WebOperationContext.Current != null)
  171. WebOperationContext.Current.OutgoingRequest.Apply (hp);
  172. // FIXME: set hp.SuppressEntityBody for some cases.
  173. ret.Properties.Add (HttpRequestMessageProperty.Name, hp);
  174. var wp = new WebBodyFormatMessageProperty (ToContentFormat (Info.IsRequestFormatSetExplicitly ? Info.RequestFormat : Behavior.DefaultOutgoingRequestFormat));
  175. ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
  176. return ret;
  177. }
  178. public object DeserializeReply (Message message, object [] parameters)
  179. {
  180. if (parameters == null)
  181. throw new ArgumentNullException ("parameters");
  182. CheckMessageVersion (message.Version);
  183. string pname = WebBodyFormatMessageProperty.Name;
  184. if (!message.Properties.ContainsKey (pname))
  185. throw new SystemException ("INTERNAL ERROR: it expects WebBodyFormatMessageProperty existence");
  186. var wp = (WebBodyFormatMessageProperty) message.Properties [pname];
  187. MessageDescription md = GetMessageDescription (MessageDirection.Output);
  188. XmlObjectSerializer serializer = null;
  189. switch (wp.Format) {
  190. case WebContentFormat.Xml:
  191. serializer = new DataContractSerializer (md.Body.ReturnValue.Type);
  192. break;
  193. case WebContentFormat.Json:
  194. serializer = new DataContractJsonSerializer (md.Body.ReturnValue.Type);
  195. break;
  196. case WebContentFormat.Raw:
  197. default:
  198. throw new NotImplementedException ();
  199. }
  200. // FIXME: handle ref/out parameters
  201. return serializer.ReadObject (message.GetReaderAtBodyContents (), false);
  202. }
  203. }
  204. internal abstract class WebDispatchMessageFormatter : WebMessageFormatter, IDispatchMessageFormatter
  205. {
  206. protected WebDispatchMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  207. : base (operation, endpoint, converter, behavior)
  208. {
  209. }
  210. public Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
  211. {
  212. try {
  213. return SerializeReplyCore (messageVersion, parameters, result);
  214. } finally {
  215. if (WebOperationContext.Current != null)
  216. OperationContext.Current.Extensions.Remove (WebOperationContext.Current);
  217. }
  218. }
  219. Message SerializeReplyCore (MessageVersion messageVersion, object [] parameters, object result)
  220. {
  221. if (parameters == null)
  222. throw new ArgumentNullException ("parameters");
  223. CheckMessageVersion (messageVersion);
  224. MessageDescription md = GetMessageDescription (MessageDirection.Output);
  225. // FIXME: use them.
  226. // var dcob = Operation.Behaviors.Find<DataContractSerializerOperationBehavior> ();
  227. // XmlObjectSerializer xos = dcob.CreateSerializer (result.GetType (), md.Body.WrapperName, md.Body.WrapperNamespace, null);
  228. // var xsob = Operation.Behaviors.Find<XmlSerializerOperationBehavior> ();
  229. // XmlSerializer [] serializers = XmlSerializer.FromMappings (xsob.GetXmlMappings ().ToArray ());
  230. WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat;
  231. string mediaType = null;
  232. XmlObjectSerializer serializer = null;
  233. switch (msgfmt) {
  234. case WebMessageFormat.Xml:
  235. serializer = new DataContractSerializer (md.Body.ReturnValue.Type);
  236. mediaType = "application/xml";
  237. break;
  238. case WebMessageFormat.Json:
  239. serializer = new DataContractJsonSerializer (md.Body.ReturnValue.Type);
  240. mediaType = "application/json";
  241. break;
  242. }
  243. // FIXME: serialize ref/out parameters as well.
  244. Message ret = Message.CreateMessage (MessageVersion.None, null, result, serializer);
  245. // Message properties
  246. var hp = new HttpResponseMessageProperty ();
  247. // FIXME: get encoding from somewhere
  248. hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8";
  249. // apply user-customized HTTP results via WebOperationContext.
  250. WebOperationContext.Current.OutgoingResponse.Apply (hp);
  251. // FIXME: fill some properties if required.
  252. ret.Properties.Add (HttpResponseMessageProperty.Name, hp);
  253. var wp = new WebBodyFormatMessageProperty (ToContentFormat (msgfmt));
  254. ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
  255. return ret;
  256. }
  257. public void DeserializeRequest (Message message, object [] parameters)
  258. {
  259. if (parameters == null)
  260. throw new ArgumentNullException ("parameters");
  261. CheckMessageVersion (message.Version);
  262. OperationContext.Current.Extensions.Add (new WebOperationContext (OperationContext.Current));
  263. IncomingWebRequestContext iwc = WebOperationContext.Current.IncomingRequest;
  264. Uri to = message.Headers.To;
  265. UriTemplateMatch match = UriTemplate.Match (Endpoint.Address.Uri, to);
  266. if (match == null)
  267. // not sure if it could happen
  268. throw new SystemException (String.Format ("INTERNAL ERROR: UriTemplate does not match with the request: {0} / {1}", UriTemplate, to));
  269. iwc.UriTemplateMatch = match;
  270. MessageDescription md = GetMessageDescription (MessageDirection.Input);
  271. for (int i = 0; i < parameters.Length; i++) {
  272. var p = md.Body.Parts [i];
  273. string name = p.Name.ToUpperInvariant ();
  274. parameters [i] = match.BoundVariables [name];
  275. }
  276. }
  277. }
  278. }
  279. }