Skip to content

Instantly share code, notes, and snippets.

@rvhuang
Created January 19, 2017 03:20
Show Gist options
  • Save rvhuang/f51b600a82e2517aabbe76bf3917ea00 to your computer and use it in GitHub Desktop.
Save rvhuang/f51b600a82e2517aabbe76bf3917ea00 to your computer and use it in GitHub Desktop.
An example of streaming a large array of objects in JSON via ASP.NET Web API.
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class ValuesController : ApiController
{
[HttpGet]
public HttpResponseMessage GetMultipartData()
{
var response = new HttpResponseMessage();
var content = new PushStreamContent(new Action<Stream, HttpContent, TransportContext>(WriteContent), "application/json");
response.Headers.TransferEncodingChunked = true;
response.Content = content;
return response;
}
public static void WriteContent(Stream stream, HttpContent content, TransportContext context)
{
var serializer = JsonSerializer.CreateDefault();
using (var sw = new StreamWriter(stream))
using (var jw = new JsonTextWriter(sw))
{
jw.WriteStartArray();
foreach (var id in Enumerable.Range(1, 100000))
{
serializer.Serialize(jw, new TestModel()
{
Alias = "rvhuang",
BirthDate = new DateTime(1985, 02, 13),
FirstName = "Robert",
LastName = "Huang",
ID = id,
MiddleName = "Vandenberg",
});
}
jw.WriteEndArray();
}
}
}
public class TestModel
{
public string FirstName
{
get; set;
}
public string MiddleName
{
get; set;
}
public DateTime BirthDate
{
get; set;
}
public string LastName
{
get; set;
}
public string Alias
{
get; set;
}
public int ID
{
get; set;
}
}
}
@alicint
Copy link

alicint commented Dec 18, 2019

any way to make it async?

@leandromoh
Copy link

There is an async overload accords to documentation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment