Last active
September 11, 2018 10:14
-
-
Save christianhelle/bc2b9751307263477042c8f958372746 to your computer and use it in GitHub Desktop.
Stream CSV from 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
[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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In this example, the component
CsvExporterService
writes a CSV string into the given stream using the data based onfoo