HttpResult.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #pragma warning disable CS1591
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Model.Services;
  8. namespace Emby.Server.Implementations.Services
  9. {
  10. public class HttpResult
  11. : IHttpResult, IAsyncStreamWriter
  12. {
  13. public HttpResult(object response, string contentType, HttpStatusCode statusCode)
  14. {
  15. this.Headers = new Dictionary<string, string>();
  16. this.Response = response;
  17. this.ContentType = contentType;
  18. this.StatusCode = statusCode;
  19. }
  20. public object Response { get; set; }
  21. public string ContentType { get; set; }
  22. public IDictionary<string, string> Headers { get; private set; }
  23. public int Status { get; set; }
  24. public HttpStatusCode StatusCode
  25. {
  26. get => (HttpStatusCode)Status;
  27. set => Status = (int)value;
  28. }
  29. public IRequest RequestContext { get; set; }
  30. public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
  31. {
  32. var response = RequestContext?.Response;
  33. if (this.Response is byte[] bytesResponse)
  34. {
  35. var contentLength = bytesResponse.Length;
  36. if (response != null)
  37. {
  38. response.ContentLength = contentLength;
  39. }
  40. if (contentLength > 0)
  41. {
  42. await responseStream.WriteAsync(bytesResponse, 0, contentLength, cancellationToken).ConfigureAwait(false);
  43. }
  44. return;
  45. }
  46. await ResponseHelper.WriteObject(this.RequestContext, this.Response, response).ConfigureAwait(false);
  47. }
  48. }
  49. }