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.

63 lines
1.8 KiB

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