Reputation: 77
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.
Upvotes: 2
Views: 600
Reputation: 9642
OutputStream - in ASP.NET Core
HttpResponse
contains Body
property to which you can write a response. ContentEncoding - set encoding for StreamWriter
since you manually write result to the response stream. In ASP.NET MVC
HttpResponse.ContentEncoding
were only used when you called HttpResponse.Write
methods.
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();
}
}
}
Update
According to source code, JsonResultExecutor
internally does exactly what I've described, only difference is it parses encoding from ContentType
.
Upvotes: 3