HttpSession.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. using System;
  2. namespace NetCoreServer
  3. {
  4. /// <summary>
  5. /// HTTP session is used to receive/send HTTP requests/responses from the connected HTTP client.
  6. /// </summary>
  7. /// <remarks>Thread-safe.</remarks>
  8. public class HttpSession : TcpSession
  9. {
  10. public HttpSession(HttpServer server) : base(server)
  11. {
  12. Cache = server.Cache;
  13. Request = new HttpRequest();
  14. Response = new HttpResponse();
  15. }
  16. /// <summary>
  17. /// Get the static content cache
  18. /// </summary>
  19. public FileCache Cache { get; }
  20. /// <summary>
  21. /// Get the HTTP request
  22. /// </summary>
  23. protected HttpRequest Request { get; }
  24. /// <summary>
  25. /// Get the HTTP response
  26. /// </summary>
  27. public HttpResponse Response { get; }
  28. #region Send response / Send response body
  29. /// <summary>
  30. /// Send the current HTTP response (synchronous)
  31. /// </summary>
  32. /// <returns>Size of sent data</returns>
  33. public long SendResponse() => SendResponse(Response);
  34. /// <summary>
  35. /// Send the HTTP response (synchronous)
  36. /// </summary>
  37. /// <param name="response">HTTP response</param>
  38. /// <returns>Size of sent data</returns>
  39. public long SendResponse(HttpResponse response) => Send(response.Cache.Data, response.Cache.Offset, response.Cache.Size);
  40. /// <summary>
  41. /// Send the HTTP response body (synchronous)
  42. /// </summary>
  43. /// <param name="body">HTTP response body</param>
  44. /// <returns>Size of sent data</returns>
  45. public long SendResponseBody(string body) => Send(body);
  46. /// <summary>
  47. /// Send the HTTP response body (synchronous)
  48. /// </summary>
  49. /// <param name="body">HTTP response body as a span of characters</param>
  50. /// <returns>Size of sent data</returns>
  51. public long SendResponseBody(ReadOnlySpan<char> body) => Send(body);
  52. /// <summary>
  53. /// Send the HTTP response body (synchronous)
  54. /// </summary>
  55. /// <param name="buffer">HTTP response body buffer</param>
  56. /// <returns>Size of sent data</returns>
  57. public long SendResponseBody(byte[] buffer) => Send(buffer);
  58. /// <summary>
  59. /// Send the HTTP response body (synchronous)
  60. /// </summary>
  61. /// <param name="buffer">HTTP response body buffer</param>
  62. /// <param name="offset">HTTP response body buffer offset</param>
  63. /// <param name="size">HTTP response body size</param>
  64. /// <returns>Size of sent data</returns>
  65. public long SendResponseBody(byte[] buffer, long offset, long size) => Send(buffer, offset, size);
  66. /// <summary>
  67. /// Send the HTTP response body (synchronous)
  68. /// </summary>
  69. /// <param name="buffer">HTTP response body buffer as a span of bytes</param>
  70. /// <returns>Size of sent data</returns>
  71. public long SendResponseBody(ReadOnlySpan<byte> buffer) => Send(buffer);
  72. /// <summary>
  73. /// Send the current HTTP response (asynchronous)
  74. /// </summary>
  75. /// <returns>'true' if the current HTTP response was successfully sent, 'false' if the session is not connected</returns>
  76. public bool SendResponseAsync() => SendResponseAsync(Response);
  77. /// <summary>
  78. /// Send the HTTP response (asynchronous)
  79. /// </summary>
  80. /// <param name="response">HTTP response</param>
  81. /// <returns>'true' if the current HTTP response was successfully sent, 'false' if the session is not connected</returns>
  82. public bool SendResponseAsync(HttpResponse response) => SendAsync(response.Cache.Data, response.Cache.Offset, response.Cache.Size);
  83. /// <summary>
  84. /// Send the HTTP response body (asynchronous)
  85. /// </summary>
  86. /// <param name="body">HTTP response body</param>
  87. /// <returns>'true' if the HTTP response body was successfully sent, 'false' if the session is not connected</returns>
  88. public bool SendResponseBodyAsync(string body) => SendAsync(body);
  89. /// <summary>
  90. /// Send the HTTP response body (asynchronous)
  91. /// </summary>
  92. /// <param name="body">HTTP response body as a span of characters</param>
  93. /// <returns>'true' if the HTTP response body was successfully sent, 'false' if the session is not connected</returns>
  94. public bool SendResponseBodyAsync(ReadOnlySpan<char> body) => SendAsync(body);
  95. /// <summary>
  96. /// Send the HTTP response body (asynchronous)
  97. /// </summary>
  98. /// <param name="buffer">HTTP response body buffer</param>
  99. /// <returns>'true' if the HTTP response body was successfully sent, 'false' if the session is not connected</returns>
  100. public bool SendResponseBodyAsync(byte[] buffer) => SendAsync(buffer);
  101. /// <summary>
  102. /// Send the HTTP response body (asynchronous)
  103. /// </summary>
  104. /// <param name="buffer">HTTP response body buffer</param>
  105. /// <param name="offset">HTTP response body buffer offset</param>
  106. /// <param name="size">HTTP response body size</param>
  107. /// <returns>'true' if the HTTP response body was successfully sent, 'false' if the session is not connected</returns>
  108. public bool SendResponseBodyAsync(byte[] buffer, long offset, long size) => SendAsync(buffer, offset, size);
  109. /// <summary>
  110. /// Send the HTTP response body (asynchronous)
  111. /// </summary>
  112. /// <param name="buffer">HTTP response body buffer as a span of bytes</param>
  113. /// <returns>'true' if the HTTP response body was successfully sent, 'false' if the session is not connected</returns>
  114. public bool SendResponseBodyAsync(ReadOnlySpan<byte> buffer) => SendAsync(buffer);
  115. #endregion
  116. #region Session handlers
  117. protected override void OnReceived(byte[] buffer, long offset, long size)
  118. {
  119. // Receive HTTP request header
  120. if (Request.IsPendingHeader())
  121. {
  122. if (Request.ReceiveHeader(buffer, (int)offset, (int)size))
  123. OnReceivedRequestHeader(Request);
  124. size = 0;
  125. }
  126. // Check for HTTP request error
  127. if (Request.IsErrorSet)
  128. {
  129. OnReceivedRequestError(Request, "Invalid HTTP request!");
  130. Request.Clear();
  131. Disconnect();
  132. return;
  133. }
  134. // Receive HTTP request body
  135. if (Request.ReceiveBody(buffer, (int)offset, (int)size))
  136. {
  137. OnReceivedRequestInternal(Request);
  138. Request.Clear();
  139. return;
  140. }
  141. // Check for HTTP request error
  142. if (Request.IsErrorSet)
  143. {
  144. OnReceivedRequestError(Request, "Invalid HTTP request!");
  145. Request.Clear();
  146. Disconnect();
  147. return;
  148. }
  149. }
  150. protected override void OnDisconnected()
  151. {
  152. // Receive HTTP request body
  153. if (Request.IsPendingBody())
  154. {
  155. OnReceivedRequestInternal(Request);
  156. Request.Clear();
  157. return;
  158. }
  159. }
  160. /// <summary>
  161. /// Handle HTTP request header received notification
  162. /// </summary>
  163. /// <remarks>Notification is called when HTTP request header was received from the client.</remarks>
  164. /// <param name="request">HTTP request</param>
  165. protected virtual void OnReceivedRequestHeader(HttpRequest request) {}
  166. /// <summary>
  167. /// Handle HTTP request received notification
  168. /// </summary>
  169. /// <remarks>Notification is called when HTTP request was received from the client.</remarks>
  170. /// <param name="request">HTTP request</param>
  171. protected virtual void OnReceivedRequest(HttpRequest request) {}
  172. /// <summary>
  173. /// Handle HTTP cached request received notification
  174. /// </summary>
  175. /// <remarks>
  176. /// Notification is called when HTTP request was received
  177. /// from the client and the corresponding cached content
  178. /// was found.
  179. ///
  180. /// Default behavior is just send cached response content
  181. /// to the client.
  182. /// </remarks>
  183. /// <param name="request">HTTP request</param>
  184. /// <param name="content">Cached response content</param>
  185. protected virtual void OnReceivedCachedRequest(HttpRequest request, byte[] content) { SendAsync(content); }
  186. /// <summary>
  187. /// Handle HTTP request error notification
  188. /// </summary>
  189. /// <remarks>Notification is called when HTTP request error was received from the client.</remarks>
  190. /// <param name="request">HTTP request</param>
  191. /// <param name="error">HTTP request error</param>
  192. protected virtual void OnReceivedRequestError(HttpRequest request, string error) {}
  193. #endregion
  194. private void OnReceivedRequestInternal(HttpRequest request)
  195. {
  196. // Try to get the cached response
  197. if (request.Method == "GET")
  198. {
  199. var index = request.Url.IndexOf('?');
  200. var response = Cache.Find((index < 0) ? request.Url : request.Url.Substring(0, index));
  201. if (response.Item1)
  202. {
  203. // Process the request with the cached response
  204. OnReceivedCachedRequest(request, response.Item2);
  205. return;
  206. }
  207. }
  208. // Process the request
  209. OnReceivedRequest(request);
  210. }
  211. }
  212. }