ResponseHelper.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Emby.Server.Implementations.HttpServer;
  9. using MediaBrowser.Model.Services;
  10. namespace Emby.Server.Implementations.Services
  11. {
  12. public static class ResponseHelper
  13. {
  14. public static Task WriteToResponse(IResponse httpRes, IRequest httpReq, object result)
  15. {
  16. if (result == null)
  17. {
  18. if (httpRes.StatusCode == (int)HttpStatusCode.OK)
  19. {
  20. httpRes.StatusCode = (int)HttpStatusCode.NoContent;
  21. }
  22. httpRes.SetContentLength(0);
  23. return Task.FromResult(true);
  24. }
  25. var httpResult = result as IHttpResult;
  26. if (httpResult != null)
  27. {
  28. httpResult.RequestContext = httpReq;
  29. httpReq.ResponseContentType = httpResult.ContentType ?? httpReq.ResponseContentType;
  30. return WriteToResponseInternal(httpRes, httpResult, httpReq);
  31. }
  32. return WriteToResponseInternal(httpRes, result, httpReq);
  33. }
  34. /// <summary>
  35. /// Writes to response.
  36. /// Response headers are customizable by implementing IHasHeaders an returning Dictionary of Http headers.
  37. /// </summary>
  38. /// <param name="response">The response.</param>
  39. /// <param name="result">Whether or not it was implicity handled by ServiceStack's built-in handlers.</param>
  40. /// <param name="request">The serialization context.</param>
  41. /// <returns></returns>
  42. private static async Task WriteToResponseInternal(IResponse response, object result, IRequest request)
  43. {
  44. var defaultContentType = request.ResponseContentType;
  45. var httpResult = result as IHttpResult;
  46. if (httpResult != null)
  47. {
  48. if (httpResult.RequestContext == null)
  49. httpResult.RequestContext = request;
  50. response.StatusCode = httpResult.Status;
  51. response.StatusDescription = httpResult.StatusCode.ToString();
  52. if (string.IsNullOrEmpty(httpResult.ContentType))
  53. {
  54. httpResult.ContentType = defaultContentType;
  55. }
  56. response.ContentType = httpResult.ContentType;
  57. if (httpResult.Cookies != null)
  58. {
  59. var httpRes = response as IHttpResponse;
  60. if (httpRes != null)
  61. {
  62. foreach (var cookie in httpResult.Cookies)
  63. {
  64. httpRes.SetCookie(cookie);
  65. }
  66. }
  67. }
  68. }
  69. var responseOptions = result as IHasHeaders;
  70. if (responseOptions != null)
  71. {
  72. foreach (var responseHeaders in responseOptions.Headers)
  73. {
  74. if (string.Equals(responseHeaders.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
  75. {
  76. response.SetContentLength(long.Parse(responseHeaders.Value));
  77. continue;
  78. }
  79. response.AddHeader(responseHeaders.Key, responseHeaders.Value);
  80. }
  81. }
  82. //ContentType='text/html' is the default for a HttpResponse
  83. //Do not override if another has been set
  84. if (response.ContentType == null || response.ContentType == "text/html")
  85. {
  86. response.ContentType = defaultContentType;
  87. }
  88. if (new HashSet<string> { "application/json", }.Contains(response.ContentType))
  89. {
  90. response.ContentType += "; charset=utf-8";
  91. }
  92. var asyncStreamWriter = result as IAsyncStreamWriter;
  93. if (asyncStreamWriter != null)
  94. {
  95. await asyncStreamWriter.WriteToAsync(response.OutputStream, CancellationToken.None).ConfigureAwait(false);
  96. return;
  97. }
  98. var streamWriter = result as IStreamWriter;
  99. if (streamWriter != null)
  100. {
  101. streamWriter.WriteTo(response.OutputStream);
  102. return;
  103. }
  104. var fileWriter = result as FileWriter;
  105. if (fileWriter != null)
  106. {
  107. await fileWriter.WriteToAsync(response, CancellationToken.None).ConfigureAwait(false);
  108. return;
  109. }
  110. var stream = result as Stream;
  111. if (stream != null)
  112. {
  113. using (stream)
  114. {
  115. await stream.CopyToAsync(response.OutputStream).ConfigureAwait(false);
  116. return;
  117. }
  118. }
  119. var bytes = result as byte[];
  120. if (bytes != null)
  121. {
  122. response.ContentType = "application/octet-stream";
  123. response.SetContentLength(bytes.Length);
  124. await response.OutputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  125. return;
  126. }
  127. var responseText = result as string;
  128. if (responseText != null)
  129. {
  130. bytes = Encoding.UTF8.GetBytes(responseText);
  131. response.SetContentLength(bytes.Length);
  132. await response.OutputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  133. return;
  134. }
  135. await WriteObject(request, result, response).ConfigureAwait(false);
  136. }
  137. public static async Task WriteObject(IRequest request, object result, IResponse response)
  138. {
  139. var contentType = request.ResponseContentType;
  140. var serializer = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
  141. using (var ms = new MemoryStream())
  142. {
  143. serializer(result, ms);
  144. ms.Position = 0;
  145. response.SetContentLength(ms.Length);
  146. await ms.CopyToAsync(response.OutputStream).ConfigureAwait(false);
  147. }
  148. //serializer(result, outputStream);
  149. }
  150. }
  151. }