WebMessageFormatter.cs 18 KB

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