For an ASP.NET Core file upload, give a minimal API endpoint an IFormFile parameter, then copy it to disk with CopyToAsync under a random file name:
app.MapPost("/upload", async (IFormFile file) =>
{
string path = Path.Combine(uploadRoot, Path.GetRandomFileName());
await using FileStream target = File.Create(path);
await file.CopyToAsync(target);
return Results.Ok(new { saved = Path.GetFileName(path), file.Length });
}).DisableAntiforgery();
I ran that on .NET 10 and got {"saved":"ejxnpqxa.uj0","length":48209} back. Below, we grow it into a real upload API with multiple files, form fields, size and type checks, and streaming for big files.
The Finished ASP.NET Core File Upload API
Here’s what we’re building. One test script sends every kind of request the API handles, and each line shows the HTTP status it got back:

/api/uploads/singletakes oneIFormFileand saves it outside the project./manyand/photostake several files throughIFormFileCollection./vendorbinds a file plus text fields into a[FromForm]record./streamreads a 40 MB file withMultipartReaderinstead of buffering it.
Before You Start: Sample Upload Files
You need the .NET 10 SDK (I used 10.0.402), VS Code and curl.exe, which ships with Windows 10 and 11. I made eight sample files with real file signatures and dummy content:
| Sample file | Size | What it tests |
|---|---|---|
| invoice-2026-11.pdf | 48 KB | a normal single upload |
| headshot.jpg, storefront.png | 116 KB, 84 KB | multiple files |
| w9-brooks-roofing.pdf | 60 KB | a file plus form fields |
| payroll-macro.exe | 23 KB | a blocked extension |
| statement.pdf | 23 KB | an .exe renamed to .pdf |
| scan-6mb.pdf | 6.0 MB | the app’s 5 MB limit |
| site-plans-40mb.pdf | 40 MB | Kestrel’s limit and streaming |
Step 1: Create the W13UploadApi Project
Start from the empty web template, not the Web API one, since we don’t need the weather sample:
dotnet new web -n W13UploadApi -o W13UploadApi
I deleted appsettings.Development.json and the Properties folder, and I start the API with dotnet run -- --urls http://localhost:5910 --environment Development. The project file is the template’s own:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>
Add an Uploads section to appsettings.json. The folder sits next to the project, not inside it, and the size cap is 5 MB:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Uploads": {
"Root": "C:\\DotNetDemo\\W13UploadApi\\uploads",
"MaxBytes": 5242880
}
}
Checkpoint: dotnet build succeeds. If the folder differs per machine, move it into appsettings per environment.
Step 2: Write the UploadStore Class
All the file handling lives in one class, so every endpoint saves and checks files the same way. Add UploadStore.cs:
namespace W13UploadApi;
public record SavedFile(string Saved, string Original, long Size, string ContentType);
public class UploadStore(IConfiguration config)
{
static readonly Dictionary<string, (string Type, byte[] Magic)> Allowed = new()
{
[".pdf"] = ("application/pdf", "%PDF"u8.ToArray()),
[".jpg"] = ("image/jpeg", [0xFF, 0xD8, 0xFF]),
[".png"] = ("image/png", [0x89, 0x50, 0x4E, 0x47]),
};
public string Root { get; } = config["Uploads:Root"]!;
readonly long maxBytes = config.GetValue<long>("Uploads:MaxBytes");
public string? Validate(IFormFile file)
{
string ext = Path.GetExtension(file.FileName).ToLowerInvariant();
if (file.Length == 0) return "The file is empty.";
if (file.Length > maxBytes) return $"The file is {file.Length / 1048576.0:0.0} MB; the limit is {maxBytes / 1048576} MB.";
if (!Allowed.TryGetValue(ext, out var rule)) return $"{ext} files aren't allowed.";
if (file.ContentType != rule.Type) return $"Content-Type {file.ContentType} doesn't match {ext}.";
byte[] head = new byte[rule.Magic.Length];
using Stream stream = file.OpenReadStream();
stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false);
return head.SequenceEqual(rule.Magic) ? null : $"The content isn't a real {ext} file.";
}
public async Task<SavedFile> SaveAsync(IFormFile file, CancellationToken ct = default)
{
Directory.CreateDirectory(Root);
string ext = Path.GetExtension(file.FileName).ToLowerInvariant();
string name = Path.ChangeExtension(Path.GetRandomFileName(), ext); // never the client's name
await using FileStream target = File.Create(Path.Combine(Root, name));
await file.CopyToAsync(target, ct);
return new(name, Path.GetFileName(file.FileName), file.Length, file.ContentType);
}
}
SaveAsync never uses the client’s file name on disk. Path.GetRandomFileName makes the name, and the original goes through Path.GetFileName, so a name like ..\..\web.config loses its path before it’s even logged.
Validate returns an error message or null. The class reads its settings through a primary constructor.
Step 3: Upload a Single File with IFormFile
Each group of endpoints gets its own file. Endpoints/SingleFile.cs maps POST /single:
namespace W13UploadApi.Endpoints;
public static class SingleFile
{
public static RouteGroupBuilder MapSingleFile(this RouteGroupBuilder api)
{
api.MapPost("/single", async (IFormFile file, UploadStore store) =>
store.Validate(file) is string error
? Results.BadRequest(new { error })
: Results.Ok(await store.SaveAsync(file)));
return api;
}
}
The parameter name file has to match the form field name. Then wire it up in Program.cs:
using W13UploadApi;
using W13UploadApi.Endpoints;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<UploadStore>();
var app = builder.Build();
RouteGroupBuilder api = app.MapGroup("/api/uploads");
api.MapSingleFile();
app.Run();
Run the API and send the invoice with curl. The findstr filter keeps the status line and the exception message:
curl.exe -s -i -F "file=@samples/invoice-2026-11.pdf" http://localhost:5910/api/uploads/single | findstr /c:"HTTP/1.1" /c:"InvalidOperationException"
Output (stack trace trimmed):
HTTP/1.1 500 Internal Server Error
Content-Type: text/plain; charset=utf-8
System.InvalidOperationException: Endpoint HTTP: POST /api/uploads/single contains anti-forgery metadata, but a middleware was not found that supports anti-forgery.

Checkpoint: a 500, and that’s expected. Since .NET 8, minimal API endpoints that bind form data (IFormFile, [FromForm]) require antiforgery validation, and the web template has no antiforgery middleware.
Step 4: Fix the IFormFile Antiforgery Error with DisableAntiforgery()
An API that callers reach with curl, a mobile app or a bearer token isn’t a CSRF target, because there’s no cookie for a forged form to ride on. So opt the group out:
RouteGroupBuilder api = app.MapGroup("/api/uploads")
.DisableAntiforgery(); // API callers send bearer tokens, not cookies
That replaces the MapGroup line in Program.cs. Send the invoice again, this time without the filter:
curl.exe -i -F "file=@samples/invoice-2026-11.pdf" http://localhost:5910/api/uploads/single
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"saved": "1pxukcj3.pdf",
"original": "invoice-2026-11.pdf",
"size": 48209,
"contentType": "application/pdf"
}

Checkpoint: 200 OK, saved as 1pxukcj3.pdf, with the original name only in the response. Your random name will differ.
If the same app serves Razor Pages or Blazor forms, keep antiforgery for those and opt out only here. With AddAntiforgery() and UseAntiforgery() but no opt-out, curl gets a 400 instead:
HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
Microsoft.AspNetCore.Http.BadHttpRequestException: Invalid anti-forgery token found when reading parameter "IFormFile file" from the request body as form.
Protect the API with tokens instead; I set that up in JWT authentication in ASP.NET Core.
Step 5: Upload Multiple Files with IFormFileCollection
For several files, bind IFormFileCollection. It holds every file in the form, whatever the field names. Add Endpoints/MultipleFiles.cs:
namespace W13UploadApi.Endpoints;
public static class MultipleFiles
{
public static RouteGroupBuilder MapMultipleFiles(this RouteGroupBuilder api)
{
// every file in the form, whatever its field name
api.MapPost("/many", async (IFormFileCollection files, UploadStore store) =>
{
var errors = files.Where(f => store.Validate(f) is not null)
.Select(f => $"{f.FileName}: {store.Validate(f)}").ToList();
if (errors.Count > 0) return Results.BadRequest(new { errors });
var saved = new List<SavedFile>();
foreach (IFormFile file in files) saved.Add(await store.SaveAsync(file));
return Results.Ok(saved);
});
// only the files sent in fields named "photos"
api.MapPost("/photos", (IFormFileCollection files) =>
{
IReadOnlyList<IFormFile> photos = files.GetFiles("photos");
return Results.Ok(new { received = photos.Count, names = photos.Select(p => p.FileName) });
});
return api;
}
}
Add api.MapMultipleFiles(); to Program.cs, then send three files in one request:
curl.exe -i -F "files=@samples/invoice-2026-11.pdf" -F "files=@samples/headshot.jpg" -F "files=@samples/storefront.png" http://localhost:5910/api/uploads/many
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
[
{
"saved": "nudgqqx5.pdf",
"original": "invoice-2026-11.pdf",
"size": 48209,
"contentType": "application/pdf"
},
{
"saved": "nymvhshj.jpg",
"original": "headshot.jpg",
"size": 118404,
"contentType": "image/jpeg"
},
{
"saved": "pwyrk5sc.png",
"original": "storefront.png",
"size": 86308,
"contentType": "image/png"
}
]

Checkpoint: an array of three saved files. The endpoint validates all of them before it saves any, so one bad file doesn’t leave half a batch on disk.
When only one field matters, filter by name with GetFiles. I sent two photos fields plus an invoice field to /photos:
{
"received": 2,
"names": [
"headshot.jpg",
"storefront.png"
]
}
Important: Microsoft Learn’s binding table lists IReadOnlyList<IFormFile> as supported, matched by field name. On .NET 10.0.13 it didn’t work for me: without [FromForm] it returned 415 Unsupported Media Type, and with [FromForm] it bound an empty list (received: 0).
List<IFormFile> also got a 415, because the minimal API read it as a JSON body. Stick with IFormFileCollection plus GetFiles until that changes.
Step 6: Send Form Fields with the File Using [FromForm]
A vendor portal needs the W-9 plus who sent it. Put the text fields and the file in one record and mark the parameter [FromForm]. Add Endpoints/FormFields.cs:
using Microsoft.AspNetCore.Mvc;
namespace W13UploadApi.Endpoints;
public record VendorDocument(string VendorName, string State, IFormFile File);
public static class FormFields
{
public static RouteGroupBuilder MapFormFields(this RouteGroupBuilder api)
{
api.MapPost("/vendor", async ([FromForm] VendorDocument doc, UploadStore store) =>
{
if (store.Validate(doc.File) is string error) return Results.BadRequest(new { error });
SavedFile saved = await store.SaveAsync(doc.File);
return Results.Ok(new { doc.VendorName, doc.State, saved.Saved, saved.Size });
});
return api;
}
}
Add api.MapFormFields(); to Program.cs and post two text fields with the PDF:
curl.exe -i -F "vendorName=Brooks Roofing LLC" -F "state=TX" -F "file=@samples/w9-brooks-roofing.pdf" http://localhost:5910/api/uploads/vendor
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"vendorName": "Brooks Roofing LLC",
"state": "TX",
"saved": "kohrhequ.pdf",
"size": 61709
}
![Minimal API [FromForm] record with IFormFile in VS Code: FormFields.cs binds VendorDocument and curl.exe sends vendorName Brooks Roofing LLC, state TX and the W-9 PDF, returning 200](https://aspdotnethelp.com/wp-content/uploads/2026/11/minimal-api-fromform-record-iformfile-form-fields-upload.png)
Checkpoint: Brooks Roofing LLC, TX and the saved name come back together. The lowercase field names matched the record’s properties. To check the text fields too, add the rules from minimal API validation.
Step 7: Validate File Size, Extension and Content Type
Now the UploadStore checks from Step 2 earn their keep. I sent four bad files to /single:
curl.exe -s -w " -> %{http_code}\n" -F "file=@samples/payroll-macro.exe" http://localhost:5910/api/uploads/single
curl.exe -s -w " -> %{http_code}\n" -F "file=@samples/statement.pdf" http://localhost:5910/api/uploads/single
curl.exe -s -w " -> %{http_code}\n" -F "file=@samples/scan-6mb.pdf" http://localhost:5910/api/uploads/single
curl.exe -s -w " -> %{http_code}\n" -F "file=@samples/site-plans-40mb.pdf" http://localhost:5910/api/uploads/single
{"error":".exe files aren't allowed."} -> 400
{"error":"The content isn't a real .pdf file."} -> 400
{"error":"The file is 6.0 MB; the limit is 5 MB."} -> 400
-> 413

Checkpoint: 400, 400, 400, 413. The renamed .exe passed the extension and content-type checks; only the file signature (the first bytes, %PDF for a PDF) caught it. The Content-Type comes from the client, so never trust it alone.
The 40 MB file never reached my code. Kestrel rejected the body, and these settings decide where that happens:
| Limit | Default | Set it with |
|---|---|---|
| Kestrel MaxRequestBodySize | 30,000,000 bytes (~28.6 MB) | ConfigureKestrel, or [RequestSizeLimit] per endpoint |
| FormOptions.MultipartBodyLengthLimit | 134,217,728 bytes (128 MB) | Configure<FormOptions>, or [RequestFormLimits] |
| FormOptions.MemoryBufferThreshold | 64 KB | larger buffered files go to a temp file |
| UploadStore check | 5 MB here | appsettings.json |
Raise the server limits only for the endpoints that need them, as Step 8 does. If your clients expect problem details for the 400s, shape them with global error handling.
Step 8: Stream Large Files with MultipartReader
An IFormFile is buffered: the whole file sits in memory or a temp file before your code runs. For big files, read the body yourself, one section at a time. Add Endpoints/Streaming.cs:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
namespace W13UploadApi.Endpoints;
public static class Streaming
{
public static RouteGroupBuilder MapStreaming(this RouteGroupBuilder api)
{
api.MapPost("/stream", async (HttpRequest request, UploadStore store) =>
{
string boundary = HeaderUtilities.RemoveQuotes(
MediaTypeHeaderValue.Parse(request.ContentType).Boundary).Value!;
var reader = new MultipartReader(boundary, request.Body);
var saved = new List<object>();
while (await reader.ReadNextSectionAsync() is { } section)
{
if (section.AsFileSection() is not { FileStream: not null } file) continue;
string name = Path.ChangeExtension(Path.GetRandomFileName(), Path.GetExtension(file.FileName));
await using FileStream target = File.Create(Path.Combine(store.Root, name));
await file.FileStream.CopyToAsync(target); // 64 KB at a time, never the whole file
saved.Add(new { saved = name, original = file.FileName, size = target.Length });
}
return Results.Ok(saved);
}).WithMetadata(new RequestSizeLimitAttribute(200_000_000));
return api;
}
}
Add api.MapStreaming(); to Program.cs. The RequestSizeLimitAttribute metadata raises Kestrel’s limit to 200 MB for this endpoint only. Then send the same 40 MB file that got a 413:
curl.exe -i -F "file=@samples/site-plans-40mb.pdf" http://localhost:5910/api/uploads/stream
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
[
{
"saved": "a55ppefj.pdf",
"original": "site-plans-40mb.pdf",
"size": 41900009
}
]

Checkpoint: 200 OK and 41,900,009 bytes on disk. Streaming doesn’t make uploads faster; it keeps big files out of memory and temp files. Add the signature checks here too before you ship it.
Test the Upload API with curl.exe
Here’s the script from the top of the post, test-uploads.cmd, in the folder above the project. The %% escapes the percent sign inside a batch file:
@echo off
rem One request per endpoint: HTTP status, route, what was sent
set API=http://localhost:5910/api/uploads
curl.exe -s -o NUL -w "%%{http_code} /single invoice-2026-11.pdf\n" -F "file=@samples/invoice-2026-11.pdf" %API%/single
curl.exe -s -o NUL -w "%%{http_code} /many 3 files\n" -F "files=@samples/invoice-2026-11.pdf" -F "files=@samples/headshot.jpg" -F "files=@samples/storefront.png" %API%/many
curl.exe -s -o NUL -w "%%{http_code} /photos 2 photos + 1 invoice\n" -F "photos=@samples/headshot.jpg" -F "photos=@samples/storefront.png" -F "invoice=@samples/invoice-2026-11.pdf" %API%/photos
curl.exe -s -o NUL -w "%%{http_code} /vendor W-9 + vendorName + state\n" -F "vendorName=Brooks Roofing LLC" -F "state=TX" -F "file=@samples/w9-brooks-roofing.pdf" %API%/vendor
curl.exe -s -o NUL -w "%%{http_code} /single payroll-macro.exe\n" -F "file=@samples/payroll-macro.exe" %API%/single
curl.exe -s -o NUL -w "%%{http_code} /single statement.pdf (an .exe inside)\n" -F "file=@samples/statement.pdf" %API%/single
curl.exe -s -o NUL -w "%%{http_code} /single scan-6mb.pdf\n" -F "file=@samples/scan-6mb.pdf" %API%/single
curl.exe -s -o NUL -w "%%{http_code} /single site-plans-40mb.pdf\n" -F "file=@samples/site-plans-40mb.pdf" %API%/single
curl.exe -s -o NUL -w "%%{http_code} /stream site-plans-40mb.pdf\n" -F "file=@samples/site-plans-40mb.pdf" %API%/stream
curl.exe -s -o NUL -w "%%{http_code} /documents headshot.jpg (controller)\n" -F "file=@samples/headshot.jpg" http://localhost:5910/api/documents
With the API running, I ran .\test-uploads.cmd from a Command Prompt in that folder. Output:
200 /single invoice-2026-11.pdf
200 /many 3 files
200 /photos 2 photos + 1 invoice
200 /vendor W-9 + vendorName + state
400 /single payroll-macro.exe
400 /single statement.pdf (an .exe inside)
400 /single scan-6mb.pdf
413 /single site-plans-40mb.pdf
200 /stream site-plans-40mb.pdf
200 /documents headshot.jpg (controller)
Every valid file got 200 and every bad one was stopped. If you’d rather click than type, publish an OpenAPI document and browse the endpoints in Scalar, as in OpenAPI and Scalar in ASP.NET Core. Then I listed the uploads folder:
02gj1nuf.pdf
3fzbxwrc.pdf
5k3vcugg.pdf
ailvpwrs.png
fxwikydv.jpg
pcuh3jwi.pdf
wgsbjoa0.jpg

Seven random names and no client file names. The rejected files were never written.
Same Upload with an [ApiController] Controller
If your API uses controllers, the code barely changes. [ApiController] infers [FromForm] for IFormFile, and my controller upload worked without any antiforgery opt-out. Add Controllers/DocumentsController.cs:
using Microsoft.AspNetCore.Mvc;
namespace W13UploadApi.Controllers;
[ApiController]
[Route("api/documents")]
public class DocumentsController(UploadStore store) : ControllerBase
{
[HttpPost]
[RequestSizeLimit(10_000_000)]
public async Task<IActionResult> Upload(IFormFile file)
{
if (store.Validate(file) is string error) return BadRequest(new { error });
return Ok(await store.SaveAsync(file));
}
}
Two lines in Program.cs turn controllers on. Here’s the finished file:
using W13UploadApi;
using W13UploadApi.Endpoints;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<UploadStore>();
builder.Services.AddControllers();
var app = builder.Build();
RouteGroupBuilder api = app.MapGroup("/api/uploads")
.DisableAntiforgery(); // API callers send bearer tokens, not cookies
api.MapSingleFile();
api.MapMultipleFiles();
api.MapFormFields();
api.MapStreaming();
app.MapControllers();
app.Run();
The headshot returned 200 from /api/documents. The 40 MB PDF hit the action’s 10 MB [RequestSizeLimit] and came back as a 400 with problem details, not a bare 413:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"": [
"Failed to read the request form. Request body too large. The max request body size is 10000000 bytes."
]
},
"traceId": "00-c551d1072..."
}
I compare the two styles in minimal APIs vs controllers.
Why Does My ASP.NET Core File Upload Fail?
500, contains anti-forgery metadata. The endpoint binds a form and nothing handles antiforgery. Call DisableAntiforgery() for token-based APIs, or UseAntiforgery() plus a real token for browser forms.
400, required parameter was not provided. The form field name doesn’t match the parameter. I sent the file as document instead of file:
HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
Microsoft.AspNetCore.Http.BadHttpRequestException: Required parameter "IFormFile file" was not provided from form file.
415 Unsupported Media Type. You sent JSON to a form endpoint, or used List<IFormFile> in a minimal API. Send multipart/form-data (curl -F) and bind IFormFileCollection.
413 Payload Too Large. That’s Kestrel’s 30,000,000-byte limit; raise it per endpoint or stream as in Step 8. On IIS, the maxAllowedContentLength setting in web.config applies too.
Note: a browser page on another origin also needs CORS to post files; see CORS in ASP.NET Core. Learn lists a file path as the request body among the features the Visual Studio .http editor doesn’t support, so test uploads with curl.exe.
Where to Take It Next
To keep files in the cloud instead of on the web server, swap the FileStream in SaveAsync for a blob upload; my Azure Blob Storage in C# guide shows the client code.
To record who uploaded what, save the random name, original name and size in a table, as in the Web API CRUD with EF Core build.
A few more posts that fit this build:
- All ASP.NET Core tutorials on AspDotnetHelp
- CancellationToken in C#, for uploads the client abandons
- ASP.NET Core middleware, where antiforgery runs
- The options pattern, a typed home for the Uploads settings
Frequently Asked Questions
How do I upload a file in ASP.NET Core Web API?
Add an IFormFile parameter to a minimal API endpoint or controller action, send multipart/form-data, and copy the file with CopyToAsync to a path you build with Path.GetRandomFileName.
How do I upload multiple files with IFormFile?
In a minimal API, bind IFormFileCollection and loop over it, or call GetFiles with a field name to get just that field’s files.
What is the maximum file upload size in ASP.NET Core?
Kestrel allows 30,000,000 bytes (about 28.6 MB) per request by default, and multipart bodies are capped at 128 MB. Raise them per endpoint with [RequestSizeLimit] and [RequestFormLimits].
Why does my IFormFile minimal API endpoint return an antiforgery error?
Since .NET 8, minimal API form binding requires antiforgery. Without the middleware you get a 500; with it but no token, a 400. Call DisableAntiforgery() on endpoints that use tokens, not cookies.
Is it safe to save an uploaded file with its original file name?
No. Treat FileName as display text only, save under a random name outside the app’s folder, and check the extension and file signature. Microsoft’s upload files in ASP.NET Core guide on Microsoft Learn has the full security checklist.
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…