You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.9 KiB

11 months ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Apewer.Web
  5. {
  6. /// <summary>表示 API 行为结果,主体为字节数组。</summary>
  7. public class BytesResult : HeadResult
  8. {
  9. #region content
  10. /// <summary>主体。</summary>
  11. public virtual byte[] Bytes { get; set; }
  12. /// <summary>创建结果实例。</summary>
  13. public BytesResult(byte[] bytes, string contentType = "application/octet-stream") : this(200, bytes, contentType) { }
  14. /// <summary>创建结果实例。</summary>
  15. public BytesResult(int status, byte[] bytes, string contentType = "application/octet-stream") : base(status)
  16. {
  17. Headers.Add("Content-Type", contentType);
  18. Bytes = bytes;
  19. }
  20. #endregion
  21. #region execute
  22. /// <summary>写入主体。</summary>
  23. /// <param name="context">API 上下文。</param>
  24. /// <param name="bodyData">主体的内容,字节数应该和 Content-Length 一致。</param>
  25. protected virtual void WriteBody(ApiContext context, byte[] bodyData)
  26. {
  27. if (bodyData != null && bodyData.Length > 0)
  28. {
  29. var stream = context.Provider.ResponseBody();
  30. stream.Write(bodyData, 0, bodyData.Length);
  31. }
  32. }
  33. /// <summary>写入 HTTP 头和主体。</summary>
  34. public override void ExecuteResult(ApiContext context)
  35. {
  36. if (Bytes == null)
  37. {
  38. WriteHead(context, 0);
  39. }
  40. else
  41. {
  42. WriteHead(context, Bytes.Length);
  43. if (Bytes.Length > 0L)
  44. {
  45. var stream = context.Provider.ResponseBody();
  46. stream.Write(Bytes);
  47. }
  48. }
  49. }
  50. #endregion
  51. }
  52. }