I try to download multiple files from a web API in .NET Core 3.1 and put them in a zip archive written in the response body. When I download the zip file with the browser the zip file is corrupted!
Controller :
public async Task DownloadFilesAsync([FromServices] IFileService fileService, [FromBody] IEnumerable<Guid> fileIds, Guid folderId)
{
HttpContext.Response.Headers.Add("Content-Disposition", $"{DispositionTypeNames.Attachment};filename*=files.zip");
HttpContext.Response.ContentType = MediaTypeNames.Application.Zip;
await fileService.GetZipAsync(User.UserId(), folderId, fileIds, HttpContext.Response.Body);
}
Service :
public async Task GetZipAsync(Guid userId, Guid folderId, IEnumerable<Guid> fileIds, Stream stream)
{
using (ZipArchive zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
{
foreach (Guid id in fileIds)
{
// metadata stored in a sql database, File is a custom type
File file = await _fileRepository.GetFileAsync(folderId, id);
using Stream entry = zip.CreateEntry(file.Name, CompressionLevel.Optimal).Open();
await _fileStorage.WriteBlobAsync(userId, folderId, file.Name, entry);
}
}
}
Storage repository :
public async Task WriteBlobAsync(Guid userId, Guid folderId, string name, Stream output)
{
BlobContainerClient container = Client.GetBlobContainerClient(userId.ToString());
await container.GetBlobClient($"{folderId}/{name}").DownloadToAsync(output);
}
But the downloaded zip archive is unusable:
What have I done wrong?