RestHandler.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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 ExceptionSerializer
  61. sealed class ExceptionSerializer
  62. {
  63. readonly Exception _e;
  64. public ExceptionSerializer (Exception e) {
  65. _e = e;
  66. }
  67. public string Message {
  68. get { return _e.Message; }
  69. }
  70. public string StackTrace {
  71. get { return _e.StackTrace; }
  72. }
  73. public string ExceptionType {
  74. get { return _e.GetType ().FullName; }
  75. }
  76. }
  77. #endregion
  78. readonly LogicalTypeInfo.LogicalMethodInfo _logicalMethodInfo;
  79. private RestHandler (HttpContext context, Type type, string filePath) {
  80. LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (type, filePath);
  81. HttpRequest request = context.Request;
  82. string methodName = request.PathInfo.Substring (1);
  83. if (logicalTypeInfo == null || String.IsNullOrEmpty(methodName))
  84. ThrowInvalidOperationException (methodName);
  85. _logicalMethodInfo = logicalTypeInfo [methodName];
  86. if (_logicalMethodInfo == null)
  87. ThrowInvalidOperationException (methodName);
  88. }
  89. static void ThrowInvalidOperationException (string pathInfo) {
  90. throw new InvalidOperationException (
  91. string.Format ("Request format is unrecognized unexpectedly ending in '{0}'.", pathInfo));
  92. }
  93. static readonly Type IRequiresSessionStateType = typeof (IRequiresSessionState);
  94. static readonly Type IReadOnlySessionStateType = typeof (IReadOnlySessionState);
  95. public static IHttpHandler GetHandler (HttpContext context, Type type, string filePath) {
  96. RestHandler handler = new RestHandler (context, type, filePath);
  97. LogicalTypeInfo.LogicalMethodInfo mi = handler._logicalMethodInfo;
  98. if (mi.MethodInfo.IsStatic) {
  99. if (IRequiresSessionStateType.IsAssignableFrom (type))
  100. return IReadOnlySessionStateType.IsAssignableFrom (type) ?
  101. new ReadOnlySessionWrapperHandler (handler) : new SessionWrapperHandler (handler);
  102. }
  103. else
  104. if (mi.WebMethod.EnableSession)
  105. return new SessionWrapperHandler (handler);
  106. return handler;
  107. }
  108. #region IHttpHandler Members
  109. public bool IsReusable {
  110. get { return false; }
  111. }
  112. public void ProcessRequest (HttpContext context) {
  113. HttpRequest request = context.Request;
  114. HttpResponse response = context.Response;
  115. response.ContentType =
  116. _logicalMethodInfo.ScriptMethod.ResponseFormat == ResponseFormat.Json ?
  117. "application/json" : "text/xml";
  118. response.Cache.SetCacheability (HttpCacheability.Private);
  119. response.Cache.SetMaxAge (TimeSpan.Zero);
  120. IDictionary<string, object> @params =
  121. "GET".Equals (request.RequestType, StringComparison.OrdinalIgnoreCase)
  122. ? GetNameValueCollectionDictionary (request.QueryString) :
  123. (IDictionary<string, object>) JavaScriptSerializer.DefaultSerializer.DeserializeObjectInternal
  124. (new StreamReader (request.InputStream, request.ContentEncoding));
  125. try {
  126. _logicalMethodInfo.Invoke (@params, response.Output);
  127. }
  128. catch (TargetInvocationException e) {
  129. response.AddHeader ("jsonerror", "true");
  130. response.ContentType = "application/json";
  131. response.StatusCode = 500;
  132. JavaScriptSerializer.DefaultSerializer.Serialize (new ExceptionSerializer (e.GetBaseException ()), response.Output);
  133. response.End ();
  134. }
  135. }
  136. IDictionary <string, object> GetNameValueCollectionDictionary (NameValueCollection nvc)
  137. {
  138. var ret = new Dictionary <string, object> ();
  139. for (int i = nvc.Count - 1; i >= 0; i--)
  140. ret.Add (nvc.GetKey (i), JavaScriptSerializer.DefaultSerializer.DeserializeObjectInternal (nvc.Get (i)));
  141. return ret;
  142. }
  143. #endregion
  144. }
  145. }