WebMessageFormatter.cs 15 KB

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