I was trying to implement a subclass of ActionResult that will stream big JSON objects from a REST API, I found this solution on stack overflow but it seems like it's an implementation for 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();
}
}
}
But when I was in the process of porting this to asp.net core MVC I found that the response class does not have ContentEncoding and OutputStream properties.
Please, can anyone provide the required changes to port this class to asp.net core?
Thanks in advance.
return Json(someObject)you get back a JsonResult object that eventually uses a JsonWriter to write to the response output stream. Have you tried returning your data in the normal way?return Json()? I posted links to the source code that show that ASP.NET Core already writes to the output stream