我试图实现一个ActionResult的子类,它将从REST API流式传输大型JSON对象,我发现这个解决方案在堆栈溢出,但它似乎是asp.net MVC的一个实现。
public class JsonStreamingResult : ActionResult
{
private IEnumerable itemsToSerialize;
public JsonStreamingResult(IEnumerable itemsToSerialize)
{
this.itemsToSerialize = itemsToSerialize;
}
public override void ExecuteResult(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/json";
response.ContentEncoding = Encoding.UTF8;
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter sw = new StreamWriter(response.OutputStream))
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.WriteStartArray();
foreach (object item in itemsToSerialize)
{
JObject obj = JObject.FromObject(item, serializer);
obj.WriteTo(writer);
writer.Flush();
}
writer.WriteEndArray();
}
}
}
但当我在将其移植到asp.net核心MVC的过程中,我发现响应类没有ContentEncoding和OutputStream属性。
请问,任何人都可以提供所需的更改来将此类移植到asp.net核心吗?
提前致谢。
OutputStream - 在ASP.NET Core
中HttpResponse
包含Body
属性,您可以在其中编写响应。 ContentEncoding - 设置StreamWriter
的编码,因为您手动将结果写入响应流。在ASP.NET MVC
中,HttpResponse.ContentEncoding
仅在您调用HttpResponse.Write
方法时使用。
public class JsonStreamingResult : ActionResult
{
private IEnumerable itemsToSerialize;
public JsonStreamingResult(IEnumerable itemsToSerialize)
{
this.itemsToSerialize = itemsToSerialize;
}
public override void ExecuteResult(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/json";
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter sw = new StreamWriter(response.Body, Encoding.UTF8))
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.WriteStartArray();
foreach (object item in itemsToSerialize)
{
JObject obj = JObject.FromObject(item, serializer);
obj.WriteTo(writer);
writer.Flush();
}
writer.WriteEndArray();
}
}
}
更新
根据source code的说法,JsonResultExecutor
内部正是我所描述的,唯一的区别是它从ContentType
解析编码。