Skip to content

Instantly share code, notes, and snippets.

@christianhelle
Last active September 11, 2018 10:14
Show Gist options
  • Save christianhelle/bc2b9751307263477042c8f958372746 to your computer and use it in GitHub Desktop.
Save christianhelle/bc2b9751307263477042c8f958372746 to your computer and use it in GitHub Desktop.
Stream CSV from Web API
[Route("foo/{id}/data/export", Name = nameof(GetCsvData))]
public async Task<HttpResponseMessage> GetCsvData(int id)
{
var foo = await FooRepository.GetByIdAsync(id);
if (foo == null)
return new HttpResponseMessage(HttpStatusCode.NoContent);
var streamContent = new PushStreamContent(async (stream, content, arg3) =>
{
try
{
await CsvExporterService.ExportAsync(foo, stream);
}
catch (Exception e)
{
Log.Write(e);
}
finally
{
stream.Close();
}
});
return CreateCsvHttpResponseMessage(streamContent);
}
private HttpResponseMessage CreateCsvHttpResponseMessage(HttpContent content)
{
var response = new HttpResponseMessage { Content = content };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
return response;
}
@christianhelle
Copy link
Author

In this example, the component CsvExporterService writes a CSV string into the given stream using the data based on foo

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