File uploads are a common feature in modern web applications. Users upload documents, images, videos, reports, backups, and other files through web interfaces and mobile applications. While uploading a small profile picture is usually straightforward, handling files that are hundreds of megabytes or several gigabytes requires a different approach.
One common mistake is reading the entire uploaded file into application memory before saving it. This may work during development with small files, but under production traffic, it can create serious memory pressure. If several users upload large files simultaneously, the application can consume excessive memory, trigger garbage collection frequently, and eventually terminate because of an out-of-memory condition.
ASP.NET Core provides streaming capabilities that allow applications to process uploaded files incrementally instead of loading the complete content into memory. However, choosing the right upload approach also involves understanding multipart form processing, request size limits, buffering, cancellation, validation, temporary storage, and concurrent uploads.
This article explains how to build a reliable large-file upload workflow in ASP.NET Core, with practical examples and production considerations.
Why Large File Uploads Consume Too Much Memory
Consider an application that allows users to upload reports or documents.
A straightforward implementation might look like this:
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
byte[] fileContent = memoryStream.ToArray();
// Process or save the file
return Ok("File uploaded successfully");
}This implementation has a potential memory problem.
The application copies the uploaded file into a MemoryStream and then calls ToArray to create another byte array containing the file data.
For a large file, the application may temporarily hold multiple copies of the same content.
For example, consider an upload of a 500 MB file. The MemoryStream can consume approximately 500 MB, and ToArray can allocate another large array. Additional memory is also required for the application, request processing, and other operations.
Now imagine that five users upload files of the same size simultaneously.
The application could require several gigabytes of memory just for these file copies.
The problem becomes worse when the application also performs operations such as:
Calculating file hashes.
Extracting ZIP archives.
Processing PDF documents.
Generating image thumbnails.
Scanning uploaded files.
Storing file content in database entities.
The solution is not simply to increase the application's memory allocation. The better approach is to avoid loading the entire file into memory in the first place.
Understand Buffering and Streaming in ASP.NET Core
ASP.NET Core supports two common approaches for receiving uploaded files: buffering and streaming.
Understanding their differences helps you choose the right implementation.
Buffered file uploads
Buffered uploads commonly use IFormFile.
For example:
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest("No file was uploaded.");
}
var filePath = Path.Combine(
"uploads",
Path.GetRandomFileName());
await using var stream = System.IO.File.Create(filePath);
await file.CopyToAsync(stream);
return Ok("Upload completed.");
}This approach is convenient because ASP.NET Core handles multipart form parsing and makes the uploaded file available through IFormFile.
However, IFormFile uploads are buffered before the action processes them. ASP.NET Core uses memory for smaller buffered content and temporary disk storage for larger content.
The default memory buffer threshold is 64 KB, and the default multipart body length limit for buffered form files is 128 MB. These are framework defaults, not recommended application-wide limits for every deployment.
Buffering is useful for small and moderately sized uploads when the application can handle the expected number of concurrent requests.
Streaming file uploads
Streaming processes incoming request content incrementally.
Instead of buffering the entire file before processing it, the application reads a small portion of the request body, writes that portion to the destination, and repeats the operation until the upload finishes.
The basic flow looks like this:
Client
|
| Upload file
v
ASP.NET Core API
|
| Read a small buffer
v
Destination Stream
|
| Write the buffer
v
File StorageThe application does not need to keep the complete file in memory.
Streaming is particularly useful when:
Users upload large documents or videos.
Multiple users upload files concurrently.
The application has limited memory resources.
Files need to be transferred directly to storage.
The application needs to calculate checksums while receiving data.
Streaming does not automatically make the network transfer faster. Its primary advantage is reducing memory and temporary buffering requirements.
Avoid MemoryStream for Large File Uploads
One of the most important improvements is to avoid copying large files into MemoryStream.
Instead of this:
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
var content = memoryStream.ToArray();Copy the content directly into a destination stream:
await using var destination = new FileStream(
filePath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None,
bufferSize: 81920,
useAsync: true);
await file.CopyToAsync(destination);This works with IFormFile, but remember that the incoming file has already passed through ASP.NET Core's buffering process.
If your application needs true streaming from the incoming HTTP request, avoid form model binding for the upload and read the request body directly.
Implement Direct Streaming in an ASP.NET Core API
For applications that receive large files from mobile clients, desktop applications, or other services, a raw request-body upload endpoint can be a straightforward solution.
The client sends the file content as the request body instead of wrapping it in multipart form data.
The following implementation streams the request body directly into a temporary file.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/files")]
public class FileUploadController : ControllerBase
{
private readonly string _uploadDirectory;
public FileUploadController(IConfiguration configuration)
{
_uploadDirectory =
configuration["FileStorage:UploadDirectory"]
?? throw new InvalidOperationException(
"Upload directory is not configured.");
}
[HttpPost("upload")]
[Consumes("application/octet-stream")]
[RequestSizeLimit(524288000)]
public async Task<IActionResult> Upload(
CancellationToken cancellationToken)
{
const long maxFileSize = 500L * 1024 * 1024;
if (Request.ContentLength is > maxFileSize)
{
return StatusCode(
StatusCodes.Status413PayloadTooLarge);
}
Directory.CreateDirectory(_uploadDirectory);
var fileName = Path.GetRandomFileName();
var temporaryPath = Path.Combine(
_uploadDirectory,
fileName + ".uploading");
var finalPath = Path.Combine(
_uploadDirectory,
fileName);
try
{
long totalBytes = 0;
await using (var destination = new FileStream(
temporaryPath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None,
bufferSize: 81920,
options: FileOptions.Asynchronous |
FileOptions.SequentialScan))
{
var buffer = new byte[81920];
while (true)
{
var bytesRead = await Request.Body.ReadAsync(
buffer.AsMemory(),
cancellationToken);
if (bytesRead == 0)
{
break;
}
totalBytes += bytesRead;
if (totalBytes > maxFileSize)
{
return StatusCode(
StatusCodes.Status413PayloadTooLarge);
}
await destination.WriteAsync(
buffer.AsMemory(0, bytesRead),
cancellationToken);
}
await destination.FlushAsync(cancellationToken);
}
System.IO.File.Move(temporaryPath, finalPath);
return Ok(new
{
FileName = fileName,
Size = totalBytes,
Message = "File uploaded successfully."
});
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception)
{
if (System.IO.File.Exists(temporaryPath))
{
System.IO.File.Delete(temporaryPath);
}
throw;
}
}
}This example demonstrates several important techniques.
Reading the request body incrementally
The application reads data into a buffer of 81,920 bytes.
var buffer = new byte[81920];It then reads the incoming request body:
var bytesRead = await Request.Body.ReadAsync(
buffer.AsMemory(),
cancellationToken);The ReadAsync method returns the number of bytes actually read. The application writes only those bytes to the destination.
await destination.WriteAsync(
buffer.AsMemory(0, bytesRead),
cancellationToken);This process continues until the request body reaches its end.
The buffer size is an example, not a universal performance setting. You can benchmark different sizes based on your storage system and workload.
Enforcing a maximum file size
The example checks Request.ContentLength before reading the request body.
However, Content-Length is not always available. Some requests can use transfer encoding without a declared content length.
That is why the application also maintains a running byte count:
totalBytes += bytesRead;
if (totalBytes > maxFileSize)
{
return StatusCode(
StatusCodes.Status413PayloadTooLarge);
}The running check prevents an upload from exceeding the application's configured limit even when the request does not provide Content-Length.
Using a temporary file
The upload is initially written to a temporary filename ending in .uploading.
After the stream is completely written and closed, the file is moved to its final name.
This prevents incomplete uploads from appearing as completed files.
For a production implementation, temporary files should also have a cleanup policy so abandoned uploads do not consume storage indefinitely.
The example uses a local filesystem. If your application runs on multiple servers or containers, use shared durable storage or object storage rather than relying on a local directory.
Upload Large Files Using MultipartReader
Many web applications use multipart/form-data because it allows a client to send files together with additional form fields.
For example, a document upload might contain:
The file itself.
A document category.
A description.
A project identifier.
The standard IFormFile model-binding approach buffers uploaded files before the controller processes them.
For true multipart streaming, use MultipartReader.
MultipartReader allows the application to read individual sections from the incoming request without first buffering the complete file through form model binding.
A simplified implementation looks like this:
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
[HttpPost("upload-multipart")]
[DisableFormValueModelBinding]
[RequestSizeLimit(524288000)]
public async Task<IActionResult> UploadMultipart(
CancellationToken cancellationToken)
{
if (!MediaTypeHeaderValue.TryParse(
Request.ContentType,
out var mediaType))
{
return BadRequest("Invalid content type.");
}
if (!string.Equals(
mediaType.MediaType.Value,
"multipart/form-data",
StringComparison.OrdinalIgnoreCase))
{
return BadRequest("Expected multipart form data.");
}
var boundary = HeaderUtilities.RemoveQuotes(
mediaType.Boundary).Value;
if (string.IsNullOrWhiteSpace(boundary))
{
return BadRequest("Multipart boundary is missing.");
}
var reader = new MultipartReader(
boundary,
Request.Body);
MultipartSection? section;
while ((section = await reader.ReadNextSectionAsync(
cancellationToken)) != null)
{
if (!ContentDispositionHeaderValue.TryParse(
section.ContentDisposition,
out var contentDisposition))
{
continue;
}
if (!contentDisposition.DispositionType.Equals(
"form-data",
StringComparison.OrdinalIgnoreCase))
{
continue;
}
var fileName = contentDisposition.FileNameStar.HasValue
? contentDisposition.FileNameStar.Value
: contentDisposition.FileName.Value;
if (string.IsNullOrWhiteSpace(fileName))
{
continue;
}
var safeName = Path.GetRandomFileName();
var filePath = Path.Combine(
_uploadDirectory,
safeName);
await using var destination = new FileStream(
filePath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None,
bufferSize: 81920,
useAsync: true);
await section.Body.CopyToAsync(
destination,
cancellationToken);
}
return Ok("Multipart upload completed.");
}The example focuses on the streaming mechanism. A production implementation must also validate the number of files, individual file sizes, allowed file types, form field sizes, and multipart section count. It should also remove incomplete files if a later section fails.
Why disable form model binding?
When an MVC action uses normal form model binding, ASP.NET Core can read and buffer the multipart request before the action executes.
If the action intends to read Request.Body directly through MultipartReader, that automatic form processing must be disabled.
The DisableFormValueModelBinding attribute is a custom resource filter that removes form value and file value provider factories.
For example:
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Method)]
public sealed class DisableFormValueModelBindingAttribute
: Attribute, IResourceFilter
{
public void OnResourceExecuting(
ResourceExecutingContext context)
{
var factories = context.ValueProviderFactories;
factories.RemoveType<FormValueProviderFactory>();
factories.RemoveType<FormFileValueProviderFactory>();
factories.RemoveType<JQueryFormValueProviderFactory>();
}
public void OnResourceExecuted(
ResourceExecutedContext context)
{
}
}This allows the action to control how the incoming multipart content is read.
If you also use antiforgery protection, design the token flow carefully. For large streamed forms, a token supplied through a request header may be more appropriate than relying on automatic form-field model binding.
Configure Request Size Limits Correctly
Streaming reduces memory consumption, but it does not automatically allow unlimited file uploads.
ASP.NET Core and the infrastructure in front of it can enforce request body size limits.
For example, Kestrel has a default maximum request body size of approximately 28.6 MB.
You can configure the application-wide limit:
builder.WebHost.ConfigureKestrel(options =>
{
options.Limits.MaxRequestBodySize =
524288000;
});This example configures a maximum request body size of 500 MB.
However, increasing the limit globally is not always desirable. An application that accepts large documents through one endpoint should not necessarily allow the same request size for every API.
For MVC actions, you can configure a per-action limit:
[RequestSizeLimit(524288000)]
public async Task<IActionResult> Upload(
CancellationToken cancellationToken)
{
// Streaming implementation
}You can also use RequestSizeLimit with a custom policy for different upload endpoints.
Do not forget the reverse proxy and web server
A request may pass through multiple layers before reaching your ASP.NET Core application.
For example:
Mobile App / Browser
|
v
Load Balancer / Reverse Proxy
|
v
IIS or Kestrel
|
v
ASP.NET Core API
|
v
File StorageEach layer may enforce its own request size limit.
For example, IIS has a request filtering limit configured through maxAllowedContentLength. Its default is approximately 28.6 MB.
If Kestrel allows 500 MB but IIS rejects requests above its own limit, the application will still fail to receive large files.
Review all relevant limits:
Layer | Setting or configuration |
|---|---|
Kestrel | MaxRequestBodySize |
MVC action | RequestSizeLimit |
IIS | maxAllowedContentLength |
IIS in-process hosting | IISServerOptions.MaxRequestBodySize |
Reverse proxy | Proxy-specific request body limit |
Cloud gateway | Gateway or ingress request size policy |
When hosting behind IIS, remember that the IIS limit may be enforced before the request reaches the application. Kestrel's request body size limit is disabled when running out-of-process behind the ASP.NET Core Module because IIS controls that limit.
The effective maximum upload size is determined by the most restrictive layer.
Choose the Right Storage Location
Streaming controls how data enters your application. You also need to decide where the uploaded content should be stored.
The most common options are local filesystem storage, database storage, and cloud object storage.
Local filesystem
For a single-server application, saving files to a dedicated directory can be a straightforward option.
var storagePath = Path.Combine(
_environment.ContentRootPath,
"AppUploads");However, storing uploads inside the application directory is not recommended. Use a dedicated storage location outside the application directory tree.
The application should have only the permissions required to write and read files. Uploaded content should never have execute permissions.
Local filesystem storage can become problematic when the application runs across multiple instances. A file written to one container may not be accessible from another container.
Database storage
A database can be appropriate for small files, especially when the content is closely associated with a database record.
However, storing large files as byte arrays can increase database size, transaction log activity, backup duration, and query overhead.
For large files, consider storing the content separately and keeping only metadata in the database.
Cloud object storage
Cloud object storage is often a better option for applications that handle large files or need to scale across multiple application instances.
For example, an application using Azure Blob Storage can stream content to a blob without first creating a complete byte array in memory.
A simplified example using the Azure Storage SDK looks like this:
var blobClient = containerClient.GetBlobClient(
Path.GetRandomFileName());
await blobClient.UploadAsync(
Request.Body,
cancellationToken);The SDK handles the transfer to blob storage. For large files, configure transfer options and validate the exact behavior of the SDK version being used.
Direct-to-storage uploads are also worth considering. The API can authorize an upload and provide a short-lived, restricted upload URL. The client then transfers the file directly to object storage rather than sending the entire file through the ASP.NET Core application.
This reduces the amount of data passing through the API server.
Validate Uploaded Files Securely
A successful file transfer does not mean the uploaded file is safe.
File uploads are a common security risk because attackers can submit files with misleading names, unexpected content, or malicious payloads.
Never trust the original filename or the content type supplied by the client.
For example, a user could upload an executable file while naming it report.pdf.
A production upload workflow should include the following checks.
Validate the file extension
Use an allowlist of extensions that your application actually supports.
var allowedExtensions = new HashSet<string>(
StringComparer.OrdinalIgnoreCase)
{
".pdf",
".jpg",
".png",
".docx"
};
var extension = Path.GetExtension(originalFileName);
if (!allowedExtensions.Contains(extension))
{
return BadRequest("File type is not allowed.");
}The filename in this example is untrusted input. Use it only for validation or display after appropriate sanitization. Never use it directly to construct the storage path.
Verify the actual file content
File extensions and MIME types are not sufficient security checks.
Inspect file signatures or magic bytes to determine whether the uploaded content matches the expected format.
For supported file types, use appropriate parsers or validation libraries. For example, an image-processing library can attempt to decode an image rather than relying only on its extension.
Scan for malware
For documents, archives, and other user-supplied files, integrate malware scanning before making the content available to other users or systems.
A common workflow is:
File Received
|
v
Temporary Storage
|
v
File Validation
|
v
Malware Scanning
|
+---- Clean ----> Approved Storage
|
+---- Unsafe ---> Quarantine / RejectThe application should not make an uploaded file publicly downloadable until validation and scanning are complete.
Generate server-side filenames
Always generate a storage filename on the server.
var storageFileName = Path.GetRandomFileName();Keep the original filename separately as metadata if the business requires it.
This prevents path traversal attacks and avoids filename collisions.
Handle Cancellation and Incomplete Uploads
Large uploads can take several minutes. During that time, users may close the browser, lose network connectivity, or cancel the operation.
The application should respond to cancellation rather than continuing to write data unnecessarily.
ASP.NET Core exposes RequestAborted through HttpContext. A CancellationToken passed to a controller action is also linked to the request's cancellation.
For example:
[HttpPost("upload")]
public async Task<IActionResult> Upload(
CancellationToken cancellationToken)
{
await using var destination = new FileStream(
filePath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None,
bufferSize: 81920,
useAsync: true);
await Request.Body.CopyToAsync(
destination,
cancellationToken);
return Ok();
}When the request is cancelled, the copy operation can stop.
However, cancellation does not automatically clean up every partially written file. Use a temporary filename and ensure incomplete uploads are removed.
A production cleanup process should periodically identify temporary files that have not been updated within an expected time window.
For long-running uploads, consider maintaining upload metadata with states such as:
Initiated
Uploading
Completed
Failed
Expired
This makes it easier to identify abandoned uploads and recover from interruptions.
Support Resumable Uploads for Very Large Files
Streaming is useful, but it does not solve every large-file upload problem.
Imagine a user uploading a 5 GB video over a mobile network. The connection drops after 4.8 GB.
With a basic upload endpoint, the user may need to start again from the beginning.
For very large files or unreliable networks, resumable uploads are a better approach.
The file is divided into smaller chunks, and each chunk is uploaded separately.
For example:
Original File: 1 GB
Chunk 1: 10 MB
Chunk 2: 10 MB
Chunk 3: 10 MB
...
Chunk 100: 10 MBThe server records which chunks have been received.
If the upload fails after chunk 75, the client can continue from chunk 76 rather than uploading the entire file again.
A resumable upload system typically needs:
A unique upload session identifier.
A defined chunk size.
Chunk numbering or byte-range information.
Server-side validation of each chunk.
Duplicate chunk detection.
Upload expiration and cleanup.
A final assembly or storage commit operation.
Integrity verification after completion.
The application should also verify the final file size and checksum before marking the upload as completed.
For cloud object storage, use the provider's multipart or block-upload capabilities where available instead of implementing chunk assembly entirely inside the API.
Manage Concurrent Uploads Without Exhausting Server Resources
Even when streaming is implemented correctly, too many simultaneous uploads can overwhelm the application.
Streaming reduces memory consumption, but every active upload still consumes resources such as:
Network bandwidth.
File handles.
Disk I/O.
Storage connections.
Request-processing capacity.
Buffer memory.
Consider an application that accepts 200 simultaneous uploads. Each upload uses an 80 KB application buffer.
The buffer allocation alone is relatively small compared with loading complete files into memory. However, the total resource consumption can still become substantial when disk writes, network activity, antivirus scanning, and other operations are included.
For production systems, consider:
Limiting concurrent uploads per user or tenant.
Applying a global upload concurrency limit.
Using quotas for total storage consumption.
Monitoring disk capacity and write latency.
Separating file scanning from the HTTP request when possible.
Moving long-running post-upload processing to background workers.
Applying rate limits to prevent abusive upload traffic.
Do not use a single fixed concurrency value for every deployment. Determine the limit through load testing against the actual storage and hosting environment.
Monitor Large File Upload Performance
A file upload endpoint should provide enough operational information to diagnose failures.
Useful metrics include:
Metric | Why it matters |
|---|---|
Upload count | Measures upload activity |
Upload success rate | Shows whether transfers complete |
Upload failure rate | Identifies recurring problems |
Average upload duration | Helps identify performance changes |
File size distribution | Shows typical and maximum upload sizes |
Concurrent uploads | Helps identify resource pressure |
Memory usage | Detects buffering and memory problems |
Temporary storage usage | Identifies abandoned or incomplete files |
Disk write latency | Helps diagnose slow storage |
HTTP 413 responses | Identifies request size limit violations |
Log upload identifiers rather than relying only on filenames. This makes it easier to trace a single upload across the API, storage provider, and background processing system.
Avoid logging file contents, authentication tokens, or sensitive document information.
For applications with large upload volumes, distributed tracing can also help identify whether delays occur while receiving data, writing to storage, scanning files, or updating database metadata.
Common Mistakes to Avoid
Mistake | Why it causes problems | Better approach |
|---|---|---|
Copying large files into MemoryStream | Creates large memory allocations | Stream directly to storage |
Calling ToArray on large streams | Creates another copy of file content | Avoid unnecessary in-memory copies |
Assuming IFormFile is true streaming | Form files are buffered before action processing | Use MultipartReader for multipart streaming |
Increasing only the Kestrel limit | IIS or a reverse proxy may still reject the request | Configure all infrastructure layers |
Trusting the original filename | Can introduce path traversal and filename collision risks | Generate server-side storage names |
Trusting the MIME type | Client-provided content types can be misleading | Validate file signatures and content |
Ignoring request cancellation | Incomplete transfers can continue consuming resources | Propagate CancellationToken |
Keeping temporary files forever | Abandoned uploads consume disk space | Implement cleanup and expiration |
Accepting unlimited concurrent uploads | Can overwhelm storage and networking resources | Apply concurrency limits and quotas |
Making files available immediately | Unsafe content may be exposed before scanning | Validate and scan before publication |
Best Practices for Production Applications
A reliable large-file upload system should combine streaming, storage design, validation, and resource management.
Follow these practices:
Use IFormFile for smaller uploads when framework buffering is acceptable.
Use direct request-body streaming or MultipartReader for large uploads.
Avoid MemoryStream and unnecessary byte-array copies for large content.
Set maximum file sizes at the application and infrastructure levels.
Store uploaded files outside the application directory.
Generate unique filenames on the server.
Validate extensions, signatures, and actual file content.
Scan files for malware before making them available.
Propagate cancellation tokens through the upload pipeline.
Use temporary storage and clean up incomplete uploads.
Consider cloud object storage for applications that run across multiple instances.
Use resumable uploads for very large files and unreliable networks.
Monitor memory, disk capacity, concurrent uploads, and upload failures.
Test with realistic file sizes and concurrent upload scenarios before production deployment.
The right implementation depends on the expected file sizes, hosting environment, storage architecture, and number of concurrent users.
Summary
Uploading large files in ASP.NET Core requires more than increasing the maximum request size. The application must also manage memory, buffering, storage, validation, and concurrent requests.
IFormFile is convenient for smaller uploads, but it uses buffering and can place pressure on memory and temporary disk storage when many large files arrive simultaneously.
For larger uploads, streaming through Request.Body or MultipartReader allows the application to process incoming data incrementally. This avoids loading the complete file into memory and provides more control over the upload process.
For production applications, combine streaming with strict size limits, safe filenames, content validation, cancellation handling, temporary-file cleanup, and appropriate storage. When files become very large or network connections are unreliable, resumable uploads and direct-to-cloud storage can provide a more scalable solution.
The most important principle is simple: receive large files as streams, keep memory usage predictable, and treat every uploaded file as untrusted input.

Join the conversation! Your thoughts help the community grow.