WebMessageFormatter.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. //
  2. // WebMessageFormatter.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2008 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. namespace System.ServiceModel.Description
  39. {
  40. internal abstract class WebMessageFormatter
  41. {
  42. OperationDescription operation;
  43. ServiceEndpoint endpoint;
  44. QueryStringConverter converter;
  45. WebHttpBehavior behavior;
  46. UriTemplate template;
  47. WebAttributeInfo info = null;
  48. public WebMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  49. {
  50. this.operation = operation;
  51. this.endpoint = endpoint;
  52. this.converter = converter;
  53. this.behavior = behavior;
  54. ApplyWebAttribute ();
  55. }
  56. void ApplyWebAttribute ()
  57. {
  58. MethodInfo mi = operation.SyncMethod ?? operation.BeginMethod;
  59. object [] atts = mi.GetCustomAttributes (typeof (WebGetAttribute), false);
  60. if (atts.Length > 0)
  61. info = ((WebGetAttribute) atts [0]).Info;
  62. atts = mi.GetCustomAttributes (typeof (WebInvokeAttribute), false);
  63. if (atts.Length > 0)
  64. info = ((WebInvokeAttribute) atts [0]).Info;
  65. if (info == null)
  66. info = new WebAttributeInfo ();
  67. template = info.BuildUriTemplate (Operation, GetMessageDescription (MessageDirection.Input));
  68. }
  69. public WebHttpBehavior Behavior {
  70. get { return behavior; }
  71. }
  72. public WebAttributeInfo Info {
  73. get { return info; }
  74. }
  75. public OperationDescription Operation {
  76. get { return operation; }
  77. }
  78. public QueryStringConverter Converter {
  79. get { return converter; }
  80. }
  81. public ServiceEndpoint Endpoint {
  82. get { return endpoint; }
  83. }
  84. public UriTemplate UriTemplate {
  85. get { return template; }
  86. }
  87. protected WebContentFormat ToContentFormat (WebMessageFormat src)
  88. {
  89. switch (src) {
  90. case WebMessageFormat.Xml:
  91. return WebContentFormat.Xml;
  92. case WebMessageFormat.Json:
  93. return WebContentFormat.Json;
  94. }
  95. throw new SystemException ("INTERNAL ERROR: should not happen");
  96. }
  97. protected void CheckMessageVersion (MessageVersion messageVersion)
  98. {
  99. if (messageVersion == null)
  100. throw new ArgumentNullException ("messageVersion");
  101. if (!MessageVersion.None.Equals (messageVersion))
  102. throw new ArgumentException ("Only MessageVersion.None is supported");
  103. }
  104. protected MessageDescription GetMessageDescription (MessageDirection dir)
  105. {
  106. foreach (MessageDescription md in operation.Messages)
  107. if (md.Direction == dir)
  108. return md;
  109. throw new SystemException ("INTERNAL ERROR: no corresponding message description for the specified direction: " + dir);
  110. }
  111. internal class RequestClientFormatter : WebClientMessageFormatter
  112. {
  113. public RequestClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  114. : base (operation, endpoint, converter, behavior)
  115. {
  116. }
  117. }
  118. internal class ReplyClientFormatter : WebClientMessageFormatter
  119. {
  120. public ReplyClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  121. : base (operation, endpoint, converter, behavior)
  122. {
  123. }
  124. }
  125. internal class RequestDispatchFormatter : WebDispatchMessageFormatter
  126. {
  127. public RequestDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  128. : base (operation, endpoint, converter, behavior)
  129. {
  130. }
  131. }
  132. internal class ReplyDispatchFormatter : WebDispatchMessageFormatter
  133. {
  134. public ReplyDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  135. : base (operation, endpoint, converter, behavior)
  136. {
  137. }
  138. }
  139. internal abstract class WebClientMessageFormatter : WebMessageFormatter, IClientMessageFormatter
  140. {
  141. protected WebClientMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  142. : base (operation, endpoint, converter, behavior)
  143. {
  144. }
  145. public Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
  146. {
  147. if (parameters == null)
  148. throw new ArgumentNullException ("parameters");
  149. CheckMessageVersion (messageVersion);
  150. var c = new NameValueCollection ();
  151. MessageDescription md = GetMessageDescription (MessageDirection.Input);
  152. if (parameters.Length != md.Body.Parts.Count)
  153. throw new ArgumentException ("Parameter array length does not match the number of message body parts");
  154. for (int i = 0; i < parameters.Length; i++) {
  155. var p = md.Body.Parts [i];
  156. string name = p.Name.ToUpperInvariant ();
  157. if (UriTemplate.PathSegmentVariableNames.Contains (name) ||
  158. UriTemplate.QueryValueVariableNames.Contains (name))
  159. c.Add (name, parameters [i] != null ? Converter.ConvertValueToString (parameters [i], parameters [i].GetType ()) : null);
  160. else
  161. // FIXME: bind as a message part
  162. 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));
  163. }
  164. Uri to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
  165. Message ret = Message.CreateMessage (messageVersion, (string) null);
  166. ret.Headers.To = to;
  167. var hp = new HttpRequestMessageProperty ();
  168. hp.Method = Info.Method;
  169. // FIXME: set hp.SuppressEntityBody for some cases.
  170. ret.Properties.Add (HttpRequestMessageProperty.Name, hp);
  171. var wp = new WebBodyFormatMessageProperty (ToContentFormat (Info.IsRequestFormatSetExplicitly ? Info.RequestFormat : Behavior.DefaultOutgoingRequestFormat));
  172. ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
  173. return ret;
  174. }
  175. public object DeserializeReply (Message message, object [] parameters)
  176. {
  177. if (parameters == null)
  178. throw new ArgumentNullException ("parameters");
  179. CheckMessageVersion (message.Version);
  180. string pname = WebBodyFormatMessageProperty.Name;
  181. if (!message.Properties.ContainsKey (pname))
  182. throw new SystemException ("INTERNAL ERROR: it expects WebBodyFormatMessageProperty existence");
  183. var wp = (WebBodyFormatMessageProperty) message.Properties [pname];
  184. MessageDescription md = GetMessageDescription (MessageDirection.Output);
  185. XmlObjectSerializer serializer = null;
  186. switch (wp.Format) {
  187. case WebContentFormat.Xml:
  188. serializer = new DataContractSerializer (md.Body.ReturnValue.Type);
  189. break;
  190. case WebContentFormat.Json:
  191. serializer = new DataContractJsonSerializer (md.Body.ReturnValue.Type);
  192. break;
  193. case WebContentFormat.Raw:
  194. default:
  195. throw new NotImplementedException ();
  196. }
  197. // FIXME: handle ref/out parameters
  198. return serializer.ReadObject (message.GetReaderAtBodyContents (), false);
  199. }
  200. }
  201. internal abstract class WebDispatchMessageFormatter : WebMessageFormatter, IDispatchMessageFormatter
  202. {
  203. protected WebDispatchMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
  204. : base (operation, endpoint, converter, behavior)
  205. {
  206. }
  207. public Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
  208. {
  209. try {
  210. return SerializeReplyCore (messageVersion, parameters, result);
  211. } finally {
  212. if (WebOperationContext.Current != null)
  213. OperationContext.Current.Extensions.Remove (WebOperationContext.Current);
  214. }
  215. }
  216. Message SerializeReplyCore (MessageVersion messageVersion, object [] parameters, object result)
  217. {
  218. if (parameters == null)
  219. throw new ArgumentNullException ("parameters");
  220. CheckMessageVersion (messageVersion);
  221. MessageDescription md = GetMessageDescription (MessageDirection.Output);
  222. // FIXME: use them.
  223. // var dcob = Operation.Behaviors.Find<DataContractSerializerOperationBehavior> ();
  224. // XmlObjectSerializer xos = dcob.CreateSerializer (result.GetType (), md.Body.WrapperName, md.Body.WrapperNamespace, null);
  225. // var xsob = Operation.Behaviors.Find<XmlSerializerOperationBehavior> ();
  226. // XmlSerializer [] serializers = XmlSerializer.FromMappings (xsob.GetXmlMappings ().ToArray ());
  227. WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat;
  228. string mediaType = null;
  229. XmlObjectSerializer serializer = null;
  230. switch (msgfmt) {
  231. case WebMessageFormat.Xml:
  232. serializer = new DataContractSerializer (md.Body.ReturnValue.Type);
  233. mediaType = "application/xml";
  234. break;
  235. case WebMessageFormat.Json:
  236. serializer = new DataContractJsonSerializer (md.Body.ReturnValue.Type);
  237. mediaType = "application/json";
  238. break;
  239. }
  240. // FIXME: serialize ref/out parameters as well.
  241. Message ret = Message.CreateMessage (MessageVersion.None, null, result, serializer);
  242. // Message properties
  243. var hp = new HttpResponseMessageProperty ();
  244. // FIXME: get encoding from somewhere
  245. hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8";
  246. // apply user-customized HTTP results via WebOperationContext.
  247. WebOperationContext.Current.OutgoingResponse.Apply (hp);
  248. // FIXME: fill some properties if required.
  249. ret.Properties.Add (HttpResponseMessageProperty.Name, hp);
  250. var wp = new WebBodyFormatMessageProperty (ToContentFormat (msgfmt));
  251. ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
  252. return ret;
  253. }
  254. public void DeserializeRequest (Message message, object [] parameters)
  255. {
  256. if (parameters == null)
  257. throw new ArgumentNullException ("parameters");
  258. CheckMessageVersion (message.Version);
  259. OperationContext.Current.Extensions.Add (new WebOperationContext (OperationContext.Current));
  260. IncomingWebRequestContext iwc = WebOperationContext.Current.IncomingRequest;
  261. Uri to = message.Headers.To;
  262. UriTemplateMatch match = UriTemplate.Match (Endpoint.Address.Uri, to);
  263. if (match == null)
  264. // not sure if it could happen
  265. throw new SystemException (String.Format ("INTERNAL ERROR: UriTemplate does not match with the request: {0} / {1}", UriTemplate, to));
  266. iwc.UriTemplateMatch = match;
  267. MessageDescription md = GetMessageDescription (MessageDirection.Input);
  268. for (int i = 0; i < parameters.Length; i++) {
  269. var p = md.Body.Parts [i];
  270. string name = p.Name.ToUpperInvariant ();
  271. parameters [i] = match.BoundVariables [name];
  272. }
  273. }
  274. }
  275. }
  276. }