WebMessageFormatter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. //
  2. // WebMessageFormatter.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2008,2009 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.Generic;
  30. using System.Globalization;
  31. using System.Reflection;
  32. using System.Runtime.Serialization;
  33. using System.Runtime.Serialization.Json;
  34. using System.ServiceModel;
  35. using System.ServiceModel.Channels;
  36. using System.ServiceModel.Dispatcher;
  37. using System.ServiceModel.Web;
  38. using System.Text;
  39. using System.Xml;
  40. namespace System.ServiceModel.Description
  41. {
  42. internal abstract class WebMessageFormatter
  43. {
  44. OperationDescription operation;
  45. ServiceEndpoint endpoint;
  46. QueryStringConverter converter;
  47. WebHttpBehavior behavior;
  48. UriTemplate template;
  49. WebAttributeInfo info = null;
  50. public WebMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  51. {
  52. this.operation = operation;
  53. this.endpoint = endpoint;
  54. this.converter = converter;
  55. this.behavior = behavior;
  56. ApplyWebAttribute ();
  57. // This is a hack for WebScriptEnablingBehavior
  58. var jqc = converter as JsonQueryStringConverter;
  59. if (jqc != null)
  60. BodyName = jqc.CustomWrapperName;
  61. }
  62. void ApplyWebAttribute ()
  63. {
  64. MethodInfo mi = operation.SyncMethod ?? operation.BeginMethod;
  65. object [] atts = mi.GetCustomAttributes (typeof (WebGetAttribute), false);
  66. if (atts.Length > 0)
  67. info = ((WebGetAttribute) atts [0]).Info;
  68. atts = mi.GetCustomAttributes (typeof (WebInvokeAttribute), false);
  69. if (atts.Length > 0)
  70. info = ((WebInvokeAttribute) atts [0]).Info;
  71. if (info == null)
  72. info = new WebAttributeInfo ();
  73. template = info.BuildUriTemplate (Operation, GetMessageDescription (MessageDirection.Input));
  74. }
  75. public string BodyName { get; set; }
  76. public WebHttpBehavior Behavior {
  77. get { return behavior; }
  78. }
  79. public WebAttributeInfo Info {
  80. get { return info; }
  81. }
  82. public WebMessageBodyStyle BodyStyle {
  83. get { return info.IsBodyStyleSetExplicitly ? info.BodyStyle : behavior.DefaultBodyStyle; }
  84. }
  85. public bool IsResponseBodyWrapped {
  86. get {
  87. switch (BodyStyle) {
  88. case WebMessageBodyStyle.Wrapped:
  89. case WebMessageBodyStyle.WrappedResponse:
  90. return true;
  91. }
  92. return BodyName != null;
  93. }
  94. }
  95. public OperationDescription Operation {
  96. get { return operation; }
  97. }
  98. public QueryStringConverter Converter {
  99. get { return converter; }
  100. }
  101. public ServiceEndpoint Endpoint {
  102. get { return endpoint; }
  103. }
  104. public UriTemplate UriTemplate {
  105. get { return template; }
  106. }
  107. protected WebContentFormat ToContentFormat (WebMessageFormat src)
  108. {
  109. switch (src) {
  110. case WebMessageFormat.Xml:
  111. return WebContentFormat.Xml;
  112. case WebMessageFormat.Json:
  113. return WebContentFormat.Json;
  114. }
  115. throw new SystemException ("INTERNAL ERROR: should not happen");
  116. }
  117. protected void CheckMessageVersion (MessageVersion messageVersion)
  118. {
  119. if (messageVersion == null)
  120. throw new ArgumentNullException ("messageVersion");
  121. if (!MessageVersion.None.Equals (messageVersion))
  122. throw new ArgumentException ("Only MessageVersion.None is supported");
  123. }
  124. protected MessageDescription GetMessageDescription (MessageDirection dir)
  125. {
  126. foreach (MessageDescription md in operation.Messages)
  127. if (md.Direction == dir)
  128. return md;
  129. throw new SystemException ("INTERNAL ERROR: no corresponding message description for the specified direction: " + dir);
  130. }
  131. protected XmlObjectSerializer GetSerializer (WebContentFormat msgfmt)
  132. {
  133. switch (msgfmt) {
  134. case WebContentFormat.Xml:
  135. if (IsResponseBodyWrapped)
  136. return GetSerializer (ref xml_serializer, p => new DataContractSerializer (p.Type, p.Name, p.Namespace));
  137. else
  138. return GetSerializer (ref xml_serializer, p => new DataContractSerializer (p.Type));
  139. break;
  140. case WebContentFormat.Json:
  141. // FIXME: after name argument they are hack
  142. #if !NET_2_1 || MONOTOUCH
  143. if (IsResponseBodyWrapped)
  144. return GetSerializer (ref json_serializer, p => new DataContractJsonSerializer (p.Type, BodyName ?? p.Name, null, 0x100000, false, null, true));
  145. else
  146. #endif
  147. return GetSerializer (ref json_serializer, p => new DataContractJsonSerializer (p.Type));
  148. break;
  149. default:
  150. throw new NotImplementedException ();
  151. }
  152. }
  153. XmlObjectSerializer xml_serializer, json_serializer;
  154. XmlObjectSerializer GetSerializer (ref XmlObjectSerializer serializer, Func<MessagePartDescription,XmlObjectSerializer> f)
  155. {
  156. if (serializer == null) {
  157. MessageDescription md = GetMessageDescription (MessageDirection.Output);
  158. serializer = f (md.Body.ReturnValue);
  159. }
  160. return serializer;
  161. }
  162. internal class RequestClientFormatter : WebClientMessageFormatter
  163. {
  164. public RequestClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  165. : base (operation, endpoint, converter, behavior)
  166. {
  167. }
  168. public override object DeserializeReply (Message message, object [] parameters)
  169. {
  170. throw new NotSupportedException ();
  171. }
  172. }
  173. internal class ReplyClientFormatter : WebClientMessageFormatter
  174. {
  175. public ReplyClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  176. : base (operation, endpoint, converter, behavior)
  177. {
  178. }
  179. public override Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
  180. {
  181. throw new NotSupportedException ();
  182. }
  183. }
  184. #if !NET_2_1
  185. internal class RequestDispatchFormatter : WebDispatchMessageFormatter
  186. {
  187. public RequestDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  188. : base (operation, endpoint, converter, behavior)
  189. {
  190. }
  191. public override Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
  192. {
  193. throw new NotSupportedException ();
  194. }
  195. }
  196. internal class ReplyDispatchFormatter : WebDispatchMessageFormatter
  197. {
  198. public ReplyDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  199. : base (operation, endpoint, converter, behavior)
  200. {
  201. }
  202. public override void DeserializeRequest (Message message, object [] parameters)
  203. {
  204. throw new NotSupportedException ();
  205. }
  206. }
  207. #endif
  208. internal abstract class WebClientMessageFormatter : WebMessageFormatter, IClientMessageFormatter
  209. {
  210. protected WebClientMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  211. : base (operation, endpoint, converter, behavior)
  212. {
  213. }
  214. public virtual Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
  215. {
  216. if (parameters == null)
  217. throw new ArgumentNullException ("parameters");
  218. CheckMessageVersion (messageVersion);
  219. var c = new Dictionary<string,string> ();
  220. MessageDescription md = GetMessageDescription (MessageDirection.Input);
  221. if (parameters.Length != md.Body.Parts.Count)
  222. throw new ArgumentException ("Parameter array length does not match the number of message body parts");
  223. for (int i = 0; i < parameters.Length; i++) {
  224. var p = md.Body.Parts [i];
  225. string name = p.Name.ToUpper (CultureInfo.InvariantCulture);
  226. if (UriTemplate.PathSegmentVariableNames.Contains (name) ||
  227. UriTemplate.QueryValueVariableNames.Contains (name))
  228. c.Add (name, parameters [i] != null ? Converter.ConvertValueToString (parameters [i], parameters [i].GetType ()) : null);
  229. else
  230. // FIXME: bind as a message part
  231. 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));
  232. }
  233. Uri to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
  234. Message ret = Message.CreateMessage (messageVersion, (string) null);
  235. ret.Headers.To = to;
  236. var hp = new HttpRequestMessageProperty ();
  237. hp.Method = Info.Method;
  238. #if !NET_2_1
  239. if (WebOperationContext.Current != null)
  240. WebOperationContext.Current.OutgoingRequest.Apply (hp);
  241. #endif
  242. // FIXME: set hp.SuppressEntityBody for some cases.
  243. ret.Properties.Add (HttpRequestMessageProperty.Name, hp);
  244. var wp = new WebBodyFormatMessageProperty (ToContentFormat (Info.IsRequestFormatSetExplicitly ? Info.RequestFormat : Behavior.DefaultOutgoingRequestFormat));
  245. ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
  246. return ret;
  247. }
  248. public virtual object DeserializeReply (Message message, object [] parameters)
  249. {
  250. if (parameters == null)
  251. throw new ArgumentNullException ("parameters");
  252. CheckMessageVersion (message.Version);
  253. string pname = WebBodyFormatMessageProperty.Name;
  254. if (!message.Properties.ContainsKey (pname))
  255. throw new SystemException ("INTERNAL ERROR: it expects WebBodyFormatMessageProperty existence");
  256. var wp = (WebBodyFormatMessageProperty) message.Properties [pname];
  257. var serializer = GetSerializer (wp.Format);
  258. // FIXME: handle ref/out parameters
  259. var md = GetMessageDescription (MessageDirection.Output);
  260. var reader = message.GetReaderAtBodyContents ();
  261. if (IsResponseBodyWrapped) {
  262. if (wp.Format == WebContentFormat.Json)
  263. reader.ReadStartElement ("root", String.Empty); // note that the wrapper name is passed to the serializer.
  264. else
  265. reader.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
  266. }
  267. var ret = serializer.ReadObject (reader, true);
  268. if (IsResponseBodyWrapped)
  269. reader.ReadEndElement ();
  270. return ret;
  271. }
  272. }
  273. internal class WrappedBodyWriter : BodyWriter
  274. {
  275. public WrappedBodyWriter (object value, XmlObjectSerializer serializer, string name, string ns, bool json)
  276. : base (true)
  277. {
  278. this.name = name;
  279. this.ns = ns;
  280. this.value = value;
  281. this.serializer = serializer;
  282. this.is_json = json;
  283. }
  284. bool is_json;
  285. string name, ns;
  286. object value;
  287. XmlObjectSerializer serializer;
  288. #if !NET_2_1
  289. protected override BodyWriter OnCreateBufferedCopy (int maxBufferSize)
  290. {
  291. return new WrappedBodyWriter (value, serializer, name, ns, is_json);
  292. }
  293. #endif
  294. protected override void OnWriteBodyContents (XmlDictionaryWriter writer)
  295. {
  296. if (is_json)
  297. WriteJsonBodyContents (writer);
  298. else
  299. WriteXmlBodyContents (writer);
  300. }
  301. void WriteJsonBodyContents (XmlDictionaryWriter writer)
  302. {
  303. if (name != null) {
  304. writer.WriteStartElement ("root");
  305. writer.WriteAttributeString ("type", "object");
  306. }
  307. serializer.WriteObject (writer, value);
  308. if (name != null)
  309. writer.WriteEndElement ();
  310. }
  311. void WriteXmlBodyContents (XmlDictionaryWriter writer)
  312. {
  313. if (name != null)
  314. writer.WriteStartElement (name, ns);
  315. serializer.WriteObject (writer, value);
  316. if (name != null)
  317. writer.WriteEndElement ();
  318. }
  319. }
  320. #if !NET_2_1
  321. internal abstract class WebDispatchMessageFormatter : WebMessageFormatter, IDispatchMessageFormatter
  322. {
  323. protected WebDispatchMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  324. : base (operation, endpoint, converter, behavior)
  325. {
  326. }
  327. public virtual Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
  328. {
  329. try {
  330. return SerializeReplyCore (messageVersion, parameters, result);
  331. } finally {
  332. if (WebOperationContext.Current != null)
  333. OperationContext.Current.Extensions.Remove (WebOperationContext.Current);
  334. }
  335. }
  336. Message SerializeReplyCore (MessageVersion messageVersion, object [] parameters, object result)
  337. {
  338. if (parameters == null)
  339. throw new ArgumentNullException ("parameters");
  340. CheckMessageVersion (messageVersion);
  341. MessageDescription md = GetMessageDescription (MessageDirection.Output);
  342. // FIXME: use them.
  343. // var dcob = Operation.Behaviors.Find<DataContractSerializerOperationBehavior> ();
  344. // XmlObjectSerializer xos = dcob.CreateSerializer (result.GetType (), md.Body.WrapperName, md.Body.WrapperNamespace, null);
  345. // var xsob = Operation.Behaviors.Find<XmlSerializerOperationBehavior> ();
  346. // XmlSerializer [] serializers = XmlSerializer.FromMappings (xsob.GetXmlMappings ().ToArray ());
  347. WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat;
  348. string mediaType = null;
  349. XmlObjectSerializer serializer = null;
  350. // FIXME: serialize ref/out parameters as well.
  351. string name = null, ns = null;
  352. switch (msgfmt) {
  353. case WebMessageFormat.Xml:
  354. serializer = GetSerializer (WebContentFormat.Xml);
  355. mediaType = "application/xml";
  356. name = IsResponseBodyWrapped ? md.Body.WrapperName : null;
  357. ns = IsResponseBodyWrapped ? md.Body.WrapperNamespace : null;
  358. break;
  359. case WebMessageFormat.Json:
  360. serializer = GetSerializer (WebContentFormat.Json);
  361. mediaType = "application/json";
  362. name = IsResponseBodyWrapped ? (BodyName ?? md.Body.ReturnValue.Name) : null;
  363. ns = String.Empty;
  364. break;
  365. }
  366. bool json = msgfmt == WebMessageFormat.Json;
  367. Message ret = Message.CreateMessage (MessageVersion.None, null, new WrappedBodyWriter (result, serializer, name, ns, json));
  368. // Message properties
  369. var hp = new HttpResponseMessageProperty ();
  370. // FIXME: get encoding from somewhere
  371. hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8";
  372. // apply user-customized HTTP results via WebOperationContext.
  373. WebOperationContext.Current.OutgoingResponse.Apply (hp);
  374. // FIXME: fill some properties if required.
  375. ret.Properties.Add (HttpResponseMessageProperty.Name, hp);
  376. var wp = new WebBodyFormatMessageProperty (ToContentFormat (msgfmt));
  377. ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
  378. return ret;
  379. }
  380. public virtual void DeserializeRequest (Message message, object [] parameters)
  381. {
  382. if (parameters == null)
  383. throw new ArgumentNullException ("parameters");
  384. CheckMessageVersion (message.Version);
  385. OperationContext.Current.Extensions.Add (new WebOperationContext (OperationContext.Current));
  386. IncomingWebRequestContext iwc = WebOperationContext.Current.IncomingRequest;
  387. Uri to = message.Headers.To;
  388. UriTemplateMatch match = UriTemplate.Match (Endpoint.Address.Uri, to);
  389. if (match == null)
  390. // not sure if it could happen
  391. throw new SystemException (String.Format ("INTERNAL ERROR: UriTemplate does not match with the request: {0} / {1}", UriTemplate, to));
  392. iwc.UriTemplateMatch = match;
  393. MessageDescription md = GetMessageDescription (MessageDirection.Input);
  394. for (int i = 0; i < parameters.Length; i++) {
  395. var p = md.Body.Parts [i];
  396. string name = p.Name.ToUpperInvariant ();
  397. var str = match.BoundVariables [name];
  398. parameters [i] = Converter.ConvertStringToValue (str, p.Type);
  399. }
  400. }
  401. }
  402. #endif
  403. }
  404. }