2
0

WebMessageFormatter.cs 17 KB

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