using Apewer.Network; using System; namespace Apewer.Web { /// 表示 API 行为结果,仅包含头。 public class HeadResult : ActionResult, IActionResult, IHttpActionResult { #region content int _status = 200; HttpHeaders _headers = new HttpHeaders(); /// 由 RFC 7231 定义的状态码。 /// 1xx (Informational)
2xx (Successful)
3xx (Redirection)
4xx (Client Error)
5xx (Server Error)
public virtual int StatusCode { get { return _status; } set { _status = value; } } /// 头部。 public virtual HttpHeaders Headers { get { return _headers; } set { _headers = value ?? new HttpHeaders(); } } /// 创建结果实例。 public HeadResult() : this(200) { } /// 创建结果实例。 public HeadResult(int status) { StatusCode = status; } #endregion #region execute /// 写入 HTTP 头。 /// API 上下文。 /// 内容长度。指定为负数时不写入 HTTP 头。 protected virtual void WriteHead(ApiContext context, long contentLength) { context.Provider.SetStatus(StatusCode); const string ContentType = "Content-Type"; const string ContentLength = "Content-Length"; foreach (var header in _headers) { if (header.Name.IsEmpty()) continue; if (header.Value.IsEmpty()) continue; // Content-Length if (ContentLength.Equals(header.Name, StringComparison.CurrentCultureIgnoreCase)) { continue; } // Content-Type if (ContentType.Equals(header.Name, StringComparison.CurrentCultureIgnoreCase)) { context.Provider.SetContentType(header.Value); continue; } // default context.Provider.SetHeader(header.Name, header.Value); } // Content-Length if (contentLength >= 0L) { context.Provider.SetContentLength(contentLength); } } /// 写入 HTTP 头,其中不包含 Content-Length。 public override void ExecuteResult(ApiContext context) { WriteHead(context, 0L); } #endregion } }