RestHandler.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. //
  2. // RestHandler.cs
  3. //
  4. // Author:
  5. // Konstantin Triger <[email protected]>
  6. //
  7. // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Text;
  32. using System.Web.Script.Serialization;
  33. using System.Collections.Specialized;
  34. using System.IO;
  35. using System.Web.SessionState;
  36. using System.Reflection;
  37. namespace System.Web.Script.Services
  38. {
  39. sealed class RestHandler : IHttpHandler
  40. {
  41. #region SessionWrappers
  42. class SessionWrapperHandler : IHttpHandler, IRequiresSessionState
  43. {
  44. readonly IHttpHandler _handler;
  45. public SessionWrapperHandler (IHttpHandler handler) {
  46. _handler = handler;
  47. }
  48. public bool IsReusable {
  49. get { return _handler.IsReusable; }
  50. }
  51. public void ProcessRequest (HttpContext context) {
  52. _handler.ProcessRequest (context);
  53. }
  54. }
  55. sealed class ReadOnlySessionWrapperHandler : SessionWrapperHandler, IReadOnlySessionState
  56. {
  57. public ReadOnlySessionWrapperHandler (IHttpHandler handler) : base (handler) { }
  58. }
  59. #endregion
  60. #region NameValueCollectionDictionary
  61. sealed class NameValueCollectionDictionary : JavaScriptSerializer.LazyDictionary
  62. {
  63. readonly NameValueCollection _nmc;
  64. public NameValueCollectionDictionary (NameValueCollection nmc) {
  65. _nmc = nmc;
  66. }
  67. protected override IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
  68. for (int i = 0, max = _nmc.Count; i < max; i++)
  69. yield return new KeyValuePair<string, object> (_nmc.GetKey (i), _nmc.Get (i));
  70. }
  71. }
  72. #endregion
  73. #region ExceptionSerializer
  74. sealed class ExceptionSerializer : JavaScriptSerializer.LazyDictionary
  75. {
  76. readonly Exception _e;
  77. public ExceptionSerializer (Exception e) {
  78. _e = e;
  79. }
  80. protected override IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
  81. yield return new KeyValuePair<string, object> ("Message", _e.Message);
  82. yield return new KeyValuePair<string, object> ("StackTrace", _e.StackTrace);
  83. yield return new KeyValuePair<string, object> ("ExceptionType", _e.GetType ().FullName);
  84. }
  85. }
  86. #endregion
  87. readonly LogicalTypeInfo.LogicalMethodInfo _logicalMethodInfo;
  88. private RestHandler (HttpContext context, Type type, string filePath) {
  89. LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (type, filePath);
  90. HttpRequest request = context.Request;
  91. if (logicalTypeInfo == null || request.PathInfo.Length < 2)
  92. ThrowInvalidOperationException (request.PathInfo);
  93. _logicalMethodInfo = logicalTypeInfo [request.PathInfo.Substring (1)];
  94. if (_logicalMethodInfo == null)
  95. ThrowInvalidOperationException (request.PathInfo);
  96. }
  97. static void ThrowInvalidOperationException (string pathInfo) {
  98. throw new InvalidOperationException (
  99. string.Format ("Request format is unrecognized unexpectedly ending in '{0}'.", pathInfo));
  100. }
  101. static readonly Type IRequiresSessionStateType = typeof (IRequiresSessionState);
  102. static readonly Type IReadOnlySessionStateType = typeof (IReadOnlySessionState);
  103. public static IHttpHandler GetHandler (HttpContext context, Type type, string filePath) {
  104. RestHandler handler = new RestHandler (context, type, filePath);
  105. LogicalTypeInfo.LogicalMethodInfo mi = handler._logicalMethodInfo;
  106. if (mi.MethodInfo.IsStatic) {
  107. if (IRequiresSessionStateType.IsAssignableFrom (type))
  108. return IReadOnlySessionStateType.IsAssignableFrom (type) ?
  109. new ReadOnlySessionWrapperHandler (handler) : new SessionWrapperHandler (handler);
  110. }
  111. else
  112. if (mi.WebMethod.EnableSession)
  113. return new SessionWrapperHandler (handler);
  114. return handler;
  115. }
  116. #region IHttpHandler Members
  117. public bool IsReusable {
  118. get { return false; }
  119. }
  120. public void ProcessRequest (HttpContext context) {
  121. HttpRequest request = context.Request;
  122. HttpResponse response = context.Response;
  123. response.ContentType =
  124. _logicalMethodInfo.ScriptMethod.ResponseFormat == ResponseFormat.Json ?
  125. "application/json" : "text/xml";
  126. response.Cache.SetCacheability (HttpCacheability.Private);
  127. response.Cache.SetMaxAge (TimeSpan.Zero);
  128. IDictionary<string, object> @params =
  129. "GET".Equals (request.RequestType, StringComparison.OrdinalIgnoreCase)
  130. ? new NameValueCollectionDictionary (request.QueryString) :
  131. (IDictionary<string, object>) JavaScriptSerializer.DefaultSerializer.DeserializeObjectInternal
  132. (new StreamReader (request.InputStream, request.ContentEncoding));
  133. try {
  134. _logicalMethodInfo.Invoke (@params, response.Output);
  135. }
  136. catch (TargetInvocationException e) {
  137. response.AddHeader ("jsonerror", "true");
  138. response.ContentType = "application/json";
  139. response.StatusCode = 500;
  140. JavaScriptSerializer.DefaultSerializer.Serialize (new ExceptionSerializer (e.GetBaseException ()), response.Output);
  141. response.End ();
  142. }
  143. }
  144. #endregion
  145. }
  146. }