using System;
using System.Collections.Generic;
using System.Text;
namespace Apewer.Web
{
/// 表示 API 行为结果,主体为字节数组。
public class BytesResult : HeadResult
{
#region content
/// 主体。
public virtual byte[] Bytes { get; set; }
/// 创建结果实例。
public BytesResult(byte[] bytes, string contentType = "application/octet-stream") : this(200, bytes, contentType) { }
/// 创建结果实例。
public BytesResult(int status, byte[] bytes, string contentType = "application/octet-stream") : base(status)
{
Headers.Add("Content-Type", contentType);
Bytes = bytes;
}
#endregion
#region execute
/// 写入主体。
/// API 上下文。
/// 主体的内容,字节数应该和 Content-Length 一致。
protected virtual void WriteBody(ApiContext context, byte[] bodyData)
{
if (bodyData != null && bodyData.Length > 0)
{
var stream = context.Provider.ResponseBody();
stream.Write(bodyData, 0, bodyData.Length);
}
}
/// 写入 HTTP 头和主体。
public override void ExecuteResult(ApiContext context)
{
if (Bytes == null)
{
WriteHead(context, 0);
}
else
{
WriteHead(context, Bytes.Length);
if (Bytes.Length > 0L)
{
var stream = context.Provider.ResponseBody();
stream.Write(Bytes);
}
}
}
#endregion
}
}