-
-
Notifications
You must be signed in to change notification settings - Fork 175
自定义内容输出
Henry edited this page Sep 10, 2019
·
1 revision
在接口通讯时往往需要响应不同格式的内容,组件虽然默认集成了JSON
格式输出;但实际情况不同情况输出的格式都可能存在差异,这个时候针对API
提供不同格式输出就非常重要.组件支持使用者自定API
输出的数据格式,只需要实现IResult
接口即可。
public interface IResult
{
IHeaderItem ContentType { get; }
int Length { get; set; }
void Setting(HttpResponse response);
bool HasBody { get; }
void Write(PipeStream stream, HttpResponse response);
}
public abstract class ResultBase : IResult
{
public virtual IHeaderItem ContentType => ContentTypes.TEXT_UTF8;
public virtual int Length { get; set; }
public virtual bool HasBody => true;
public virtual void Setting(HttpResponse response)
{
}
public virtual void Write(PipeStream stream, HttpResponse response)
{
}
}
public class NotFoundResult : ResultBase
{
public NotFoundResult(string message)
{
Message = message;
}
public NotFoundResult(string formater, params object[] data) : this(string.Format(formater, data)) { }
public string Message { get; set; }
public override bool HasBody => true;
public override void Setting(HttpResponse response)
{
response.Request.Server.RequestError();
response.Code = "404";
response.CodeMsg = "not found";
response.Request.ClearStream();
}
public override void Write(PipeStream stream, HttpResponse response)
{
stream.Write(Message);
}
}
public class JsonResult : ResultBase
{
public JsonResult(object data)
{
Data = data;
}
public object Data { get; set; }
public override IHeaderItem ContentType => ContentTypes.JSON;
public override bool HasBody => true;
public override void Write(PipeStream stream, HttpResponse response)
{
using (stream.LockFree())
{
response.JsonSerializer.Serialize(response.JsonWriter, Data);
response.JsonWriter.Flush();
}
}
}
public object json(IHttpContext context)
{
return new JsonResult(new JsonMessage { message = "Hello, World!" });
}
public class DownLoad : BeetleX.FastHttpApi.IResult
{
public DownLoad(string text)
{
Text = text;
}
public string Text { get; set; }
public IHeaderItem ContentType => ContentTypes.OCTET_STREAM;
public int Length { get; set; }
public bool HasBody => true;
public void Setting(HttpResponse response)
{
response.Header.Add("Content-Disposition", "attachment;filename=TcpBanchmarks.json");
}
public void Write(PipeStream stream, HttpResponse response)
{
stream.Write(Text);
}
}
}
public object Download()
{
var items = Service.Default.GetStore();
string text = Newtonsoft.Json.JsonConvert.SerializeObject(items);
return new DownLoad(text);
}