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.

92 lines
2.7 KiB

8 months ago
  1. using Apewer.Network;
  2. using System;
  3. namespace Apewer.Web
  4. {
  5. /// <summary>表示 API 行为结果,仅包含头。</summary>
  6. public class HeadResult : ActionResult, IActionResult, IHttpActionResult
  7. {
  8. #region content
  9. int _status = 200;
  10. HttpHeaders _headers = new HttpHeaders();
  11. /// <summary>由 RFC 7231 定义的状态码。</summary>
  12. /// <value>1xx (Informational)<br />2xx (Successful)<br />3xx (Redirection)<br />4xx (Client Error)<br />5xx (Server Error)</value>
  13. public virtual int StatusCode
  14. {
  15. get { return _status; }
  16. set { _status = value; }
  17. }
  18. /// <summary>头部。</summary>
  19. public virtual HttpHeaders Headers
  20. {
  21. get { return _headers; }
  22. set { _headers = value ?? new HttpHeaders(); }
  23. }
  24. /// <summary>创建结果实例。</summary>
  25. public HeadResult() : this(200) { }
  26. /// <summary>创建结果实例。</summary>
  27. public HeadResult(int status)
  28. {
  29. StatusCode = status;
  30. }
  31. #endregion
  32. #region execute
  33. /// <summary>写入 HTTP 头。</summary>
  34. /// <param name="context">API 上下文。</param>
  35. /// <param name="contentLength">内容长度。指定为负数时不写入 HTTP 头。</param>
  36. protected virtual void WriteHead(ApiContext context, long contentLength)
  37. {
  38. context.Provider.SetStatus(StatusCode);
  39. const string ContentType = "Content-Type";
  40. const string ContentLength = "Content-Length";
  41. foreach (var header in _headers)
  42. {
  43. if (header.Name.IsEmpty()) continue;
  44. if (header.Value.IsEmpty()) continue;
  45. // Content-Length
  46. if (ContentLength.Equals(header.Name, StringComparison.CurrentCultureIgnoreCase))
  47. {
  48. continue;
  49. }
  50. // Content-Type
  51. if (ContentType.Equals(header.Name, StringComparison.CurrentCultureIgnoreCase))
  52. {
  53. context.Provider.SetContentType(header.Value);
  54. continue;
  55. }
  56. // default
  57. context.Provider.SetHeader(header.Name, header.Value);
  58. }
  59. // Content-Length
  60. if (contentLength >= 0L)
  61. {
  62. context.Provider.SetContentLength(contentLength);
  63. }
  64. }
  65. /// <summary>写入 HTTP 头,其中不包含 Content-Length。</summary>
  66. public override void ExecuteResult(ApiContext context)
  67. {
  68. WriteHead(context, 0L);
  69. }
  70. #endregion
  71. }
  72. }