WebMessageFormatter.cs 14 KB

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