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

using Apewer.Network;
using System;
namespace Apewer.Web
{
/// <summary>表示 API 行为结果,仅包含头。</summary>
public class HeadResult : ActionResult, IActionResult, IHttpActionResult
{
#region content
int _status = 200;
HttpHeaders _headers = new HttpHeaders();
/// <summary>由 RFC 7231 定义的状态码。</summary>
/// <value>1xx (Informational)<br />2xx (Successful)<br />3xx (Redirection)<br />4xx (Client Error)<br />5xx (Server Error)</value>
public virtual int StatusCode
{
get { return _status; }
set { _status = value; }
}
/// <summary>头部。</summary>
public virtual HttpHeaders Headers
{
get { return _headers; }
set { _headers = value ?? new HttpHeaders(); }
}
/// <summary>创建结果实例。</summary>
public HeadResult() : this(200) { }
/// <summary>创建结果实例。</summary>
public HeadResult(int status)
{
StatusCode = status;
}
#endregion
#region execute
/// <summary>写入 HTTP 头。</summary>
/// <param name="context">API 上下文。</param>
/// <param name="contentLength">内容长度。指定为负数时不写入 HTTP 头。</param>
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);
}
}
/// <summary>写入 HTTP 头,其中不包含 Content-Length。</summary>
public override void ExecuteResult(ApiContext context)
{
WriteHead(context, 0L);
}
#endregion
}
}