WebMessageFormatter.cs 16 KB

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