Large file uploads in ASP.NET Core: IFormFile buffering to memory and temp disk (FormOptions.MemoryBufferThreshold, MultipartBodyLengthLimit), streaming with MultipartReader or Request.Body/BodyReader, Kestrel MaxRequestBodySize and per-endpoint overrides, MinRequestBodyDataRate, proxy and IIS limits, direct-to-Blob uploads with SAS, validation, malware scanning and anti-forgery.
With IFormFile, ASP.NET Core buffers the whole multipart body before your handler runs: in memory up to 64 KB per file (FormOptions.MemoryBufferThreshold), then to temp files on disk. That's fine for small files, but for 2 GB uploads it means disk, I/O, latency and a denial-of-service risk. Instead I stream: read the body with MultipartReader (or the raw Request.Body) and copy each section straight to Blob Storage, so memory stays flat regardless of size. Then I align limits at every hop: Kestrel MaxRequestBodySize (~28.6 MB default), MultipartBodyLengthLimit (128 MB), IIS and the ingress or gateway, raising them per endpoint only. For truly large files, the best option is often a SAS URL so the client uploads directly to storage. The trade-off: streaming is more code but scales; buffering is simple but only for small files.
"The key thing to know about
IFormFileis when the bytes are read. Form binding reads the entire multipart body before your handler runs. Each file is held in memory up to 64 KB, then spilled to a temp file. So for a 2 GB upload, the request spends minutes writing to the server's temp disk before my code sees it, ten concurrent uploads need 20 GB of disk, and anyone can exhaust it.IFormFileis fine for avatars and small documents, not for this.For large files I stream. I disable form binding on that endpoint, read the boundary from the
Content-Type, and useMultipartReaderto walk the sections. For each file section I validate the declared size, check the first bytes for the expected file signature, then copy the section's stream straight to Blob Storage withBlobClient.UploadAsync(stream), which uploads in blocks. Memory stays at a few buffers per request. Then I deal with limits at every layer: Kestrel'sMaxRequestBodySizeis about 28.6 MB by default,FormOptions.MultipartBodyLengthLimitis 128 MB, IIS hasmaxAllowedContentLength, and the ingress or Application Gateway has its own body limit. I raise them only on the upload endpoint with[RequestSizeLimit], and keepMinRequestBodyDataRateon so slow trickling clients can't hold connections forever.For example, [at company] [a document intake API] crashed pods with
No space left on devicewhen [an insurer] bulk-uploaded scanned files through anIFormFileendpoint. I changed it to stream withMultipartReaderinto Blob Storage and, for files over [100 MB], moved to a two-step flow where the API issues a short-lived, write-only SAS URL and the client uploads directly. [Pod disk use stayed flat and upload success went from about 92% to over 99.5%.] The mistake I see is raising the size limits and keepingIFormFile. The bytes still go to disk; you've just made the disk fill faster."
IFormFile (buffered) |
MultipartReader / raw body (streamed) |
Direct to Blob via SAS | |
|---|---|---|---|
| When bytes are read | Before the handler runs | As your code reads | Never through the API |
| Memory/disk | 64 KB memory per file, rest temp disk | Constant (buffers only) | None on API |
| Code complexity | Lowest | Medium | Medium (two-step flow) |
| Good for | < ~10 MB files | Up to GBs through the API | Very large files, high volume |
| Validation | After upload | During upload (can abort early) | After upload (storage events) |
| Layer | Setting | Default |
|---|---|---|
| Kestrel | MaxRequestBodySize / [RequestSizeLimit] |
30,000,000 bytes |
| Forms | FormOptions.MultipartBodyLengthLimit |
128 MB |
| Forms | MemoryBufferThreshold |
64 KB |
| IIS | requestFiltering/requestLimits maxAllowedContentLength |
~28.6 MB |
| ingress-nginx | proxy-body-size annotation |
1 MB |
| Azure Application Gateway (WAF) | Max request body / file upload size | Depends on SKU and WAF policy |
Switching a 500 MB scan upload from IFormFile to streaming cut peak pod temp disk from about 6 GB under load to near zero and memory per upload to under 1 MB; moving the largest files to SAS direct uploads removed about 70% of ingress bandwidth from the API pods.
Checks deep understanding of how request bodies are read and the judgement to design large uploads safely.
Green flags
IFormFile buffers before the handler and spills to disk after 64 KB.MultipartReader or the raw body and keeps memory flat.Red flags
MemoryStream.Request body (multipart/form-data)
└► FormFeature.ReadFormAsync() ← triggered by IFormFile / [FromForm] / Request.Form
└► MultipartReader over the body
├─ form fields ─► memory (limits: ValueCountLimit, ValueLengthLimit)
└─ file sections ─► FileBufferingReadStream
├─ ≤ 64 KB: memory
└─ > 64 KB: temp file (ASPNETCORE_TEMP or system temp)
└► your handler runs ONLY after the whole body has been read
Temp files are deleted at the end of the request. On containers with small ephemeral storage, concurrent large uploads fill the disk and the pod is evicted.
MultipartReader(boundary, Request.Body) returns MultipartSections one at a time. Each section has headers (Content-Disposition with name and filename) and a Body stream that reads directly from the request. You must consume or skip each section before reading the next. Form binding must not run first, otherwise the body is already consumed: in MVC remove value providers with a [DisableFormValueModelBinding] resource filter; in Minimal APIs take HttpRequest and don't declare IFormFile parameters.
For a single file, the simplest streaming option is PUT /files/{name} with the file as the raw body (Content-Type: application/octet-stream) and await request.Body.CopyToAsync(destination, ct), or request.BodyReader with pipelines for maximum efficiency.
Client ─POST /uploads─► API: authorise, create record, issue SAS (write-only, 15 min, one blob)
Client ─PUT (blocks)──► Azure Blob Storage
Storage ─BlobCreated event─► Event Grid ─► worker: scan, validate, mark record ready
Use user delegation SAS (signed with Entra ID) rather than account-key SAS. Defender for Storage malware scanning can scan on upload.
FileName or ContentType: generate the stored name, check magic bytes (%PDF, \x89PNG), enforce size while streaming (count bytes and abort).Content-Disposition: attachment.IFormFile validate anti-forgery tokens by default since .NET 8 (DisableAntiforgery() for token-authenticated APIs).A 2 GB upload at 20 Mbit/s takes about 15 minutes. Check proxy and load balancer timeouts, keep MinRequestBodyDataRate (240 B/s) so stalled clients are dropped, and consider resumable uploads (Blob block lists, or the tus protocol) for unreliable networks.
IFormFile endpoint and watch the temp directory and dotnet-counters working set.MultipartReader and compare memory and disk..exe as .pdf and confirm your magic-byte check rejects it.Streaming multipart uploads to Blob Storage with size and signature checks, plus a SAS endpoint for direct uploads.
// Program.cs
using Azure.Storage.Blobs;
using Azure.Storage.Sas;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(_ => new BlobServiceClient(
new Uri(builder.Configuration["Storage:BlobEndpoint"]!), new Azure.Identity.DefaultAzureCredential()));
builder.WebHost.ConfigureKestrel(k => k.Limits.MaxRequestBodySize = 1 * 1024 * 1024); // small global default
var app = builder.Build();
const long MaxFileBytes = 2L * 1024 * 1024 * 1024; // 2 GB
// Streamed upload: no IFormFile, so the framework never buffers the body
app.MapPost("/documents", async (HttpRequest request, BlobServiceClient blobs, CancellationToken ct) =>
{
if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaType) ||
!mediaType.MediaType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
return Results.Problem("Expected multipart/form-data.", statusCode: 415);
var boundary = HeaderUtilities.RemoveQuotes(mediaType.Boundary).Value!;
var reader = new MultipartReader(boundary, request.Body);
var container = blobs.GetBlobContainerClient("incoming");
var stored = new List<string>();
while (await reader.ReadNextSectionAsync(ct) is { } section)
{
if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var cd) || !cd.IsFileDisposition())
continue; // skip non-file fields (or read them as needed)
var blobName = $"{Guid.NewGuid():N}.pdf"; // never trust the client's file name
await using var limited = new SignatureCheckingStream(section.Body, MaxFileBytes, "%PDF"u8.ToArray());
await container.GetBlobClient(blobName).UploadAsync(limited, cancellationToken: ct); // block upload, constant memory
stored.Add(blobName);
}
return Results.Accepted(value: stored);
})
.WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(MaxFileBytes + 1024 * 1024)) // this endpoint only
.RequireAuthorization();
// Direct-to-storage: client gets a short-lived, write-only SAS for one blob
app.MapPost("/uploads", async (BlobServiceClient blobs, CancellationToken ct) =>
{
var key = await blobs.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddMinutes(15), ct);
var blob = blobs.GetBlobContainerClient("incoming").GetBlobClient($"{Guid.NewGuid():N}");
var sas = new BlobSasBuilder(BlobSasPermissions.Create | BlobSasPermissions.Write, DateTimeOffset.UtcNow.AddMinutes(15))
{
BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name
};
var uri = new BlobUriBuilder(blob.Uri) { Sas = sas.ToSasQueryParameters(key.Value, blobs.AccountName) }.ToUri();
return Results.Ok(new { uploadUrl = uri });
}).RequireAuthorization();
app.Run();
// Enforces a size limit and checks the file signature while streaming, so bad uploads abort early
public sealed class SignatureCheckingStream(Stream inner, long maxBytes, byte[] signature) : Stream
{
private long _read;
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken ct = default)
{
var n = await inner.ReadAsync(buffer, ct);
if (_read < signature.Length && n > 0)
{
var check = Math.Min(n, signature.Length - (int)_read);
if (!buffer.Span[..check].SequenceEqual(signature.AsSpan((int)_read, check)))
throw new BadHttpRequestException("File type not allowed.", 415);
}
_read += n;
if (_read > maxBytes) throw new BadHttpRequestException("File too large.", 413);
return n;
}
public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult();
public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => _read; set => throw new NotSupportedException(); }
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
IFormFile for large files. Why it is wrong: The whole body is still buffered to temp storage before your code runs; on containers that is small ephemeral storage, so pods get evicted. Instead: Stream with MultipartReader or the raw body, or upload directly to storage.MaxRequestBodySize globally. Why it is wrong: Every endpoint now accepts huge bodies, an easy denial of service. Instead: Small global limit; [RequestSizeLimit] on the upload endpoint.FileName and ContentType. Why it is wrong: Both are client-controlled; path traversal and disguised executables follow. Instead: Generate names, check magic bytes, scan for malware.Request.Form or declaring IFormFile on a streaming endpoint. Why it is wrong: Accessing the form makes the framework read and buffer the entire body first, so by the time MultipartReader runs the body is consumed and the memory/disk cost has already been paid. Instead: Take HttpRequest only (Minimal APIs) or disable form value binding (MVC).Read, CopyTo) on the request body. Why it is wrong: Kestrel disallows synchronous I/O by default (AllowSynchronousIO = false) and, if enabled, a slow 15-minute upload pins a ThreadPool thread the whole time. Instead: ReadAsync/CopyToAsync with the request's CancellationToken.MemoryStream or byte[]. Why it is wrong: Memory grows with file size and concurrency, and large arrays land on the LOH. Instead: Stream to the destination.wwwroot. Why it is wrong: They become publicly downloadable and possibly executable. Instead: Private storage served through an authorised endpoint.The senior question isn't 'how do I accept a big file' but 'should these bytes go through my API at all?'. API pods are expensive places to move gigabytes: they tie up connections, bandwidth and disk, and scale poorly. Direct-to-storage with SAS plus an event-driven scan is usually the best design for large files; streaming through the API is right when you must inspect or transform data inline, and IFormFile is right for small files where simplicity wins. Whatever you choose, test with real sizes through the real ingress, and watch disk, memory and upload success rate in production.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
IFormFile |
Small files (< ~10 MB), low volume | Temp disk, buffering latency | Large or high-volume uploads |
Streaming through API (MultipartReader/raw body) |
Inline validation or transformation | More code, long-lived connections | Very high volume of huge files |
| SAS direct to Blob + events | Large files, high volume, mobile clients | Two-step flow, async processing | When the API must reject content before storing |
| Resumable uploads (block lists, tus) | Unreliable networks, multi-GB files | Client complexity | Small files |
Kestrel's KestrelServerLimits are mostly protective limits against resource exhaustion and denial of service, not speed settings. MaxConcurrentConnections and MaxConcurrentUpgradedConnections are unlimited (null) by default; MaxRequestBodySize defaults to about 28.6 MB (30,000,000 bytes) and should be overridden per endpoint for uploads; header limits (32 KB total, 100 headers), RequestHeadersTimeout (30 s) and MinRequestBodyDataRate (240 bytes/s) protect against slow-client attacks; KeepAliveTimeout (130 s) must outlive the proxy's idle timeout. HTTP/2 allows 100 streams per connection with flow-control windows; HTTP/3 must be enabled explicitly and needs HTTPS, UDP open on the port and libmsquic on Linux. In practice, Kestrel is rarely the bottleneck: throughput is limited by downstream I/O, ThreadPool starvation, CPU in serialisation, allocations/GC and connection pools. Tighten limits for safety, but measure with dotnet-counters before tuning for speed.
Model binding takes data from the request (route values, query string, headers, form fields, the JSON body) and from DI, converts it, and passes it to your handler's parameters. You can be explicit with [FromRoute], [FromQuery], [FromHeader], [FromForm], [FromBody] and [FromServices], or let the framework infer. In Minimal APIs: a parameter named in the route template comes from the route, other simple types from the query, registered services from DI, and complex types from the JSON body. In controllers with [ApiController]: complex types from the body, IFormFile from the form, route names from the route, the rest from the query. Only one parameter can read the body. [AsParameters] groups parameters into a record. The trade-off: inference keeps code short, but explicit attributes make the contract obvious in reviews and OpenAPI.
How to tell it (STAR)
**S:** Our [document intake API] used IFormFile with raised limits, and when [an insurer] bulk-uploaded scans, pods were evicted for running out of disk. **T:** I owned making uploads reliable at any size. **A:** I proved the body was buffered to temp disk before our code ran, rewrote the endpoint to stream into Blob Storage with size and signature checks, restored small global limits, and added a SAS direct-upload path for the largest files. **R:** Pod disk use stayed flat, upload success went from [about 92%] to [over 99.5%], and the API pods stopped carrying [most] of the upload bandwidth.
Last updated 23 Nov 2026.