Exporting hundreds of thousands of rows to CSV or bundling multiple report files into a ZIP archive is a classic place where ASP.NET Core MVC applications hit memory spikes, Large Object Heap (LOH) fragmentation, or slow time-to-first-byte (TTFB). A naive implementation that materializes an entire List<T> into memory, builds a giant StringBuilder or MemoryStream, and only then returns File(...) holds the whole payload in RAM per concurrent export—and delays sending the first byte until every row is finished.
Streaming directly to the HTTP response body (HttpContext.Response.Body / PipeWriter) using an asynchronous database stream (IAsyncEnumerable<T>) and System.IO.Compression.ZipArchive flips that model. Rows flow from the database cursor through CSV formatting and ZIP compression straight onto the network socket with natural backpressure when the client or proxy reads slowly, keeping memory usage nearly flat regardless of export size.
1. Architectural Blueprint & Backpressure Flow
Plaintext
[Database / Data Source]
│ AsNoTracking().AsAsyncEnumerable() (streams rows in batches)
▼
[Streamed Export Service]
├─ CSV Formatter: writes UTF-8 CSV rows incrementally to a StreamWriter
└─ ZIP Bundler: creates ZipArchiveEntry items on a non-leaving/controlled stream
▼
[HttpContext.Response.Body]
├─ Flushes chunks progressively to client / reverse proxy
└─ Respects HttpContext.RequestAborted (stops early if client disconnects)
Pattern |
Buffering Strategy |
Memory Profile Under Large Exports |
Time-to-First-Byte |
Materialize + MemoryStream |
Loads all rows + full serialized/compressed bytes in memory before sending. |
Spikes linearly with row count & file size; risks LOH pressure and OOMs. |
High (waits for full generation). |
Async Cursor + Streaming CSV / ZipArchive |
Streams rows via IAsyncEnumerable<T> and writes entries progressively to response body. |
Low and bounded by buffer/chunk sizes across concurrent requests. |
Fast (headers and early chunks flush promptly). |
2. Domain Contracts, Record Model, and Streaming Data Source
Let's define an AuditRecord projection, a CSV escaping helper (including formula-injection neutralization for leading =, +, -, @, tab, or carriage-return characters), and an IAuditExportSource abstraction that yields rows asynchronously via IAsyncEnumerable<T>.
C#
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
public sealed record AuditRecord(
long SequenceId,
DateTimeOffset OccurredAtUtc,
string Actor,
string Action,
string ResourcePath,
decimal Amount
);
public interface IAuditExportSource
{
IAsyncEnumerable<AuditRecord> StreamRecordsAsync(
DateTimeOffset fromUtc,
DateTimeOffset toUtc,
[EnumeratorCancellation] CancellationToken cancellationToken = default);
}
public sealed class SampleAuditExportSource : IAuditExportSource
{
private readonly int _totalRows;
public SampleAuditExportSource(int totalRows = 25_000)
{
_totalRows = totalRows;
}
public async IAsyncEnumerable<AuditRecord> StreamRecordsAsync(
DateTimeOffset fromUtc,
DateTimeOffset toUtc,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
DateTimeOffset baseTime = fromUtc == default ? DateTimeOffset.UtcNow.AddDays(-7) : fromUtc;
for (int i = 1; i <= _totalRows; i++)
{
cancellationToken.ThrowIfCancellationRequested();
if (i % 5_000 == 0)
{
await Task.Yield();
}
yield return new AuditRecord(
SequenceId: i,
OccurredAtUtc: baseTime.AddSeconds(i),
Actor: $"operator_{(i % 50) + 1:D2}",
Action: i % 2 == 0 ? "RECORD_APPROVED" : "RECORD_SUBMITTED",
ResourcePath: $"/records/{100_000 + i}",
Amount: decimal.Round((i % 950) + 12.50m, 2, MidpointRounding.AwayFromZero));
}
}
}
public static class CsvFormatting
{
private static readonly char[] FormulaTriggerChars = ['=', '+', '-', '@', '\t', '\r'];
public static string Escape(string? value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
string safeValue = value;
if (Array.IndexOf(FormulaTriggerChars, safeValue[0]) >= 0)
{
safeValue = "'" + safeValue;
}
bool requiresQuotes = safeValue.IndexOfAny([',', '"', '\r', '\n']) >= 0;
if (!requiresQuotes)
{
return safeValue;
}
return $"\"{safeValue.Replace("\"", "\"\"", StringComparison.Ordinal)}\"";
}
public static string FormatHeader() =>
"SequenceId,OccurredAtUtc,Actor,Action,ResourcePath,Amount";
public static string FormatRow(AuditRecord record)
{
string timestamp = record.OccurredAtUtc.ToString("O", CultureInfo.InvariantCulture);
string amount = record.Amount.ToString("0.00", CultureInfo.InvariantCulture);
return string.Join(
',',
record.SequenceId.ToString(CultureInfo.InvariantCulture),
Escape(timestamp),
Escape(record.Actor),
Escape(record.Action),
Escape(record.ResourcePath),
amount);
}
}
3. Streaming CSV Writer and Streaming Multi-Entry ZIP Archiver
Two practical streaming details matter when writing to an ASP.NET Core HTTP response stream:
Synchronous vs. Asynchronous Stream Writes: ZipArchive and StreamWriter write chunks into an underlying stream. In ASP.NET Core, enabling synchronous I/O only on the response feature when needed—or writing via a buffered stream/pipe—avoids Synchronous operations are disallowed exceptions if a sync write occurs under Kestrel or test servers.
ZIP Central Directory: A ZIP archive writes its central directory at the end of the archive stream, so ZipArchive must be disposed before the response finishes so the central directory and end-of-central-directory record are flushed completely to the client.
C#
using System.IO.Compression;
using System.Text;
public sealed class ExportStreamingService
{
private const int BufferSize = 64 * 1024;
private static readonly UTF8Encoding Utf8WithoutBom = new(encoderShouldEmitUTF8Identifier: false);
private readonly IAuditExportSource _exportSource;
private readonly ILogger<ExportStreamingService> _logger;
public ExportStreamingService(
IAuditExportSource exportSource,
ILogger<ExportStreamingService> logger)
{
_exportSource = exportSource;
_logger = logger;
}
public async Task WriteCsvAsync(
Stream targetStream,
DateTimeOffset fromUtc,
DateTimeOffset toUtc,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(targetStream);
await using var writer = new StreamWriter(
targetStream,
Utf8WithoutBom,
bufferSize: BufferSize,
leaveOpen: true);
await writer.WriteLineAsync(CsvFormatting.FormatHeader().AsMemory(), cancellationToken);
long rowCount = 0;
await foreach (AuditRecord record in _exportSource
.StreamRecordsAsync(fromUtc, toUtc, cancellationToken)
.WithCancellation(cancellationToken))
{
await writer.WriteLineAsync(CsvFormatting.FormatRow(record).AsMemory(), cancellationToken);
rowCount++;
if (rowCount % 1_000 == 0)
{
await writer.FlushAsync(cancellationToken);
}
}
await writer.FlushAsync(cancellationToken);
_logger.LogInformation("Streamed CSV export with {RowCount} rows.", rowCount);
}
public async Task WriteZipBundleAsync(
Stream targetStream,
DateTimeOffset fromUtc,
DateTimeOffset toUtc,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(targetStream);
await using var bufferedTarget = new BufferedStream(targetStream, BufferSize);
using var archive = new ZipArchive(bufferedTarget, ZipArchiveMode.Create, leaveOpen: true);
// Entry 1: Full CSV dataset
ZipArchiveEntry csvEntry = archive.CreateEntry("audit-records.csv", CompressionLevel.Fastest);
await using (Stream entryStream = csvEntry.Open())
await using (var csvWriter = new StreamWriter(entryStream, Utf8WithoutBom, bufferSize: BufferSize, leaveOpen: true))
{
await csvWriter.WriteLineAsync(CsvFormatting.FormatHeader().AsMemory(), cancellationToken);
long count = 0;
await foreach (AuditRecord record in _exportSource
.StreamRecordsAsync(fromUtc, toUtc, cancellationToken)
.WithCancellation(cancellationToken))
{
await csvWriter.WriteLineAsync(CsvFormatting.FormatRow(record).AsMemory(), cancellationToken);
count++;
if (count % 1_000 == 0)
{
await csvWriter.FlushAsync(cancellationToken);
}
}
await csvWriter.FlushAsync(cancellationToken);
}
// Entry 2: Export manifest metadata
ZipArchiveEntry manifestEntry = archive.CreateEntry("export-manifest.txt", CompressionLevel.Fastest);
await using (Stream manifestStream = manifestEntry.Open())
await using (var manifestWriter = new StreamWriter(manifestStream, Utf8WithoutBom, bufferSize: BufferSize, leaveOpen: true))
{
await manifestWriter.WriteLineAsync($"GeneratedAtUtc: {DateTimeOffset.UtcNow:O}");
await manifestWriter.WriteLineAsync($"FromUtc: {fromUtc:O}");
await manifestWriter.WriteLineAsync($"ToUtc: {toUtc:O}");
await manifestWriter.FlushAsync(cancellationToken);
}
// Dispose ZipArchive before flushing bufferedTarget so ZIP central directory is written
archive.Dispose();
await bufferedTarget.FlushAsync(cancellationToken);
_logger.LogInformation("Streamed ZIP archive export completed.");
}
}
4. MVC Controller Actions and Program.cs Setup
In an MVC controller, setting Content-Type, Content-Disposition (attachment; filename="..."), and X-Content-Type-Options: nosniff before writing to Response.Body ensures browsers download the streamed CSV or ZIP file cleanly without guessing MIME types.
Controller (ExportsController.cs)
C#
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/exports")]
public sealed class ExportsController : ControllerBase
{
private readonly ExportStreamingService _exportService;
public ExportsController(ExportStreamingService exportService)
{
_exportService = exportService;
}
[HttpGet("audit.csv")]
public async Task DownloadCsv(
[FromQuery] DateTimeOffset? fromUtc,
[FromQuery] DateTimeOffset? toUtc,
CancellationToken cancellationToken)
{
var syncIoFeature = HttpContext.Features.Get<IHttpBodyControlFeature>();
if (syncIoFeature is not null)
{
syncIoFeature.AllowSynchronousIO = true;
}
Response.StatusCode = StatusCodes.Status200OK;
Response.ContentType = "text/csv; charset=utf-8";
Response.Headers.ContentDisposition = "attachment; filename=\"audit-export.csv\"";
Response.Headers["X-Content-Type-Options"] = "nosniff";
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken,
HttpContext.RequestAborted);
await _exportService.WriteCsvAsync(
Response.Body,
fromUtc ?? DateTimeOffset.UtcNow.AddDays(-7),
toUtc ?? DateTimeOffset.UtcNow,
linkedCts.Token);
}
[HttpGet("audit-bundle.zip")]
public async Task DownloadZip(
[FromQuery] DateTimeOffset? fromUtc,
[FromQuery] DateTimeOffset? toUtc,
CancellationToken cancellationToken)
{
var syncIoFeature = HttpContext.Features.Get<IHttpBodyControlFeature>();
if (syncIoFeature is not null)
{
syncIoFeature.AllowSynchronousIO = true;
}
Response.StatusCode = StatusCodes.Status200OK;
Response.ContentType = "application/zip";
Response.Headers.ContentDisposition = "attachment; filename=\"audit-bundle.zip\"";
Response.Headers["X-Content-Type-Options"] = "nosniff";
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken,
HttpContext.RequestAborted);
await _exportService.WriteZipBundleAsync(
Response.Body,
fromUtc ?? DateTimeOffset.UtcNow.AddDays(-7),
toUtc ?? DateTimeOffset.UtcNow,
linkedCts.Token);
}
}
Application Wiring (Program.cs)
C#
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IAuditExportSource>(new SampleAuditExportSource(totalRows: 25_000));
builder.Services.AddScoped<ExportStreamingService>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();
app.Run();
public partial class Program { }
5. End-to-End Integration Testing with WebApplicationFactory<Program>
Using HttpCompletionOption.ResponseHeadersRead and reading from GetStreamAsync() lets you test real streaming responses end-to-end and inspect entries inside the generated ZIP archive with ZipArchive:
C#
using System.IO.Compression;
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class ExportsControllerIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public ExportsControllerIntegrationTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task DownloadCsv_StreamsHeaderAndRowsWithAttachmentHeaders()
{
using HttpClient client = _factory.CreateClient();
using HttpResponseMessage response = await client.GetAsync(
"/api/exports/audit.csv",
HttpCompletionOption.ResponseHeadersRead);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/csv", response.Content.Headers.ContentType?.MediaType);
Assert.Equal("attachment", response.Content.Headers.ContentDisposition?.DispositionType);
await using Stream stream = await response.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
string? headerLine = await reader.ReadLineAsync();
Assert.Equal("SequenceId,OccurredAtUtc,Actor,Action,ResourcePath,Amount", headerLine);
string? firstDataLine = await reader.ReadLineAsync();
Assert.False(string.IsNullOrWhiteSpace(firstDataLine));
Assert.StartsWith("1,", firstDataLine);
}
[Fact]
public async Task DownloadZip_StreamsValidArchiveContainingCsvAndManifest()
{
using HttpClient client = _factory.CreateClient();
using HttpResponseMessage response = await client.GetAsync(
"/api/exports/audit-bundle.zip",
HttpCompletionOption.ResponseHeadersRead);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/zip", response.Content.Headers.ContentType?.MediaType);
await using Stream networkStream = await response.Content.ReadAsStreamAsync();
await using var memoryCopy = new MemoryStream();
await networkStream.CopyToAsync(memoryCopy);
memoryCopy.Position = 0;
using var zipArchive = new ZipArchive(memoryCopy, ZipArchiveMode.Read);
var entryNames = zipArchive.Entries.Select(e => e.FullName).ToList();
Assert.Contains("audit-records.csv", entryNames);
Assert.Contains("export-manifest.txt", entryNames);
}
}
6. Conclusion
Streaming large CSV exports and ZIP archives directly to the ASP.NET Core MVC response stream—driven by IAsyncEnumerable<T> and bounded buffers rather than full-payload MemoryStream buffering—keeps memory usage predictable under heavy export workloads and delivers faster time-to-first-byte. Pairing proper CSV escaping, Content-Disposition headers, client-disconnect cancellation (RequestAborted), and proper ZipArchive disposal before final flush gives you reliable, production-grade file exports without memory spikes.
Join the conversation! Your thoughts help the community grow.