I have a Web API 2 ApiController
with the following GET method:
[HttpGet]
public IHttpActionResult GetZip()
{
return new ZipFileActionResult();
}
My custom implementation of IHttpActionResult
public class ZipFileActionResult : IHttpActionResult
{
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var memoryStream = new MemoryStream();
var response = new HttpResponseMessage(HttpStatusCode.OK);
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var entry = archive.CreateEntry("MyFileName.txt");
using (var streamWriter = new StreamWriter(entry.Open()))
{
streamWriter.Write("It was the best of times, it was the worst of times...");
}
}
response.Content = new StreamContent(memoryStream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "example.zip"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return Task.FromResult(response);
}
}
When I use Postman to GET, I get "No response". A breakpoint where StreamContent
is created shows the stream to have a length around 1000 bytes. What have I missed?
Other similar questions but not duplicates
This question is not a duplicate, although it appears to have some siblings:
- ZipArchive creates invalid ZIP file but I'm not saving to windows so I don't have a file stream. I am also ensuring that the stream remains open after the
ZipArchive
as disposed. - Writing to ZipArchive using the HttpContext OutputStream but I am not writing straight out to the
HttpContext.OutputStream
, as I am streaming toStreamContent
, I can use the simplerMemoryStream
.