Created
January 19, 2017 03:20
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
any way to make it async?