HttpResult.cs 1.7 KB

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