File uploads
suggest changeA browser uploads files with an HTML form that uses enctype="multipart/form-data". The request body is split into parts. Each part is a form field or a file, and each file part carries the field name, the original file name and a content type.
ASP.NET Core gives you three ways to receive uploads:
IFormFile: the framework parses the whole form for you. Simple, and the right choice for small and medium files.MultipartReader: you read the parts one at a time as they arrive. Use it for large files you don't want buffered.- raw request body: the client sends the file as the whole body (
PUT /files/report.csv). Simplest of all, but there's no room for extra form fields.
On the client side, HttpClient sends multipart requests with MultipartFormDataContent.
Every example below is a complete program: it starts a small ASP.NET Core app (dotnet new web), uploads to it with HttpClient, prints the results and stops. All were run with .NET 10.
1. What a multipart request looks like
MultipartFormDataContent builds the body. You normally let it pick a random boundary, but a fixed one makes the output easy to read:
using System.Net.Http.Headers;
using var form = new MultipartFormDataContent("----demo-boundary");
form.Add(new StringContent("Quarterly report"), "title");
var file = new ByteArrayContent("a,b\n1,2\n"u8.ToArray());
file.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
form.Add(file, "file", "data.csv");
Console.WriteLine($"Content-Type: {form.Headers.ContentType}");
Console.WriteLine();
Console.Write(await form.ReadAsStringAsync());
Output:
Content-Type: multipart/form-data; boundary="----demo-boundary"
------demo-boundary
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=title
Quarterly report
------demo-boundary
Content-Type: text/csv
Content-Disposition: form-data; name=file; filename=data.csv; filename*=utf-8''data.csv
a,b
1,2
------demo-boundary--
form.Add(content, name)adds a regular field,form.Add(content, name, fileName)adds a file. Thefilenameparameter inContent-Dispositionis what makes a part a file.- Parts are separated by
--+ boundary, and the body ends with--+ boundary +--. filename*=utf-8''...is the RFC 5987 encoding, so non-ASCII file names survive.- Set the content type of each file part yourself.
ByteArrayContentandStreamContentdon't set one, and the server then sees an emptyContentType.
2. Receiving a single file with IFormFile
In a minimal API, a parameter of type IFormFile is bound from the form part whose name matches the parameter name:
using System.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
var app = builder.Build();
app.MapPost("/upload", async (IFormFile file) =>
{
// Read the uploaded file as text (fine for small files)
using var reader = new StreamReader(file.OpenReadStream());
string text = await reader.ReadToEndAsync();
return $"name={file.Name} fileName={file.FileName} type={file.ContentType} " +
$"length={file.Length} content=\"{text}\"";
}).DisableAntiforgery(); // API endpoint called by non-browser clients
const string baseUrl = "http://localhost:5417";
app.Urls.Add(baseUrl);
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
using var form = new MultipartFormDataContent();
var fileContent = new ByteArrayContent("hello upload"u8.ToArray());
fileContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
form.Add(fileContent, "file", "notes.txt"); // field name, file name
var resp = await http.PostAsync("/upload", form);
Console.WriteLine($"{(int)resp.StatusCode} {await resp.Content.ReadAsStringAsync()}");
await app.StopAsync();
Output:
200 name=file fileName=notes.txt type=text/plain length=12 content="hello upload"
IFormFile members:
| Member | Meaning |
|---|---|
Name |
Form field name (file) |
FileName |
File name sent by the client. Untrusted |
ContentType |
Content type sent by the client. Untrusted |
Length |
Size in bytes |
OpenReadStream() |
Read the content |
CopyToAsync(stream) |
Copy the content to another stream, e.g. a FileStream |
Headers, ContentDisposition |
Raw headers of the part |
Notes:
.DisableAntiforgery()is required here. Since .NET 8, minimal API endpoints that bind form data (IFormFile,IFormFileCollection,[FromForm]) carry antiforgery metadata. Without antiforgery middleware the request fails with a 500 andInvalidOperationException: Endpoint HTTP: POST /upload contains anti-forgery metadata, but a middleware was not found that supports anti-forgery. For an API used by non-browser clients, disable it. For browser forms, use it (section 7).- By the time the handler runs, the whole form has been read. Parts up to 64 KB are kept in memory and bigger ones are buffered to a temporary file (in the directory set by
ASPNETCORE_TEMP, or the system temp directory). It is deleted at the end of the request, so copy the file somewhere if you want to keep it.
3. Multiple files and form fields
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
var app = builder.Build();
// 1. All files from the form, whatever their field names
app.MapPost("/many", (IFormFileCollection files) =>
string.Join("\n", files.Select(f => $" {f.Name}: {f.FileName} ({f.Length} bytes)")))
.DisableAntiforgery();
// 2. Named form fields and files bound to parameters
app.MapPost("/album", ([FromForm] AlbumInfo info, IFormFile cover, IFormFileCollection files) =>
{
IReadOnlyList<IFormFile> photos = files.GetFiles("photos"); // only the "photos" parts
return $" title={info.Title} public={info.IsPublic} cover={cover.FileName} " +
$"photos=[{string.Join(", ", photos.Select(p => p.FileName))}]";
}).DisableAntiforgery();
// 3. Low level: read the whole form yourself
app.MapPost("/raw-form", async (HttpRequest req) =>
{
if (!req.HasFormContentType) return Results.BadRequest("expected a form");
IFormCollection form = await req.ReadFormAsync();
var fields = form.Select(kv => $"{kv.Key}={kv.Value}");
var files = form.Files.Select(f => $"{f.Name}:{f.FileName}");
return Results.Text($" fields: {string.Join(", ", fields)}\n files: {string.Join(", ", files)}");
}).DisableAntiforgery();
const string baseUrl = "http://localhost:5418";
app.Urls.Add(baseUrl);
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
static ByteArrayContent FilePart(string text, string mediaType)
{
var c = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(text));
c.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
return c;
}
MultipartFormDataContent NewForm()
{
var form = new MultipartFormDataContent();
form.Add(new StringContent("Holidays"), "title");
form.Add(new StringContent("true"), "isPublic");
form.Add(FilePart("cover", "image/jpeg"), "cover", "cover.jpg");
form.Add(FilePart("photo one", "image/jpeg"), "photos", "beach.jpg");
form.Add(FilePart("photo two!", "image/jpeg"), "photos", "sunset.jpg");
return form;
}
foreach (var path in new[] { "/many", "/album", "/raw-form" })
{
using var form = NewForm();
var resp = await http.PostAsync(path, form);
Console.WriteLine($"{path} -> {(int)resp.StatusCode}");
Console.WriteLine(await resp.Content.ReadAsStringAsync());
}
await app.StopAsync();
record AlbumInfo(string Title, bool IsPublic);
Output:
/many -> 200
cover: cover.jpg (5 bytes)
photos: beach.jpg (9 bytes)
photos: sunset.jpg (10 bytes)
/album -> 200
title=Holidays public=True cover=cover.jpg photos=[beach.jpg, sunset.jpg]
/raw-form -> 200
fields: title=Holidays, isPublic=true
files: cover:cover.jpg, photos:beach.jpg, photos:sunset.jpg
Things to know:
- To send several files under one field name, call
form.Addseveral times with the same name. That's what<input type="file" name="photos" multiple>does in a browser. - An
IFormFileCollectionparameter gets all files of the request, no matter the field name. UseGetFiles("photos")to pick the ones of a single field, andGetFile("cover")for the first file with a name. [FromForm] AlbumInfo infobinds regular fields to a type, matching names case-insensitively.- In minimal APIs a
List<IFormFile>orIFormFile[]property of a[FromForm]type is not bound (it staysnull). UseIFormFileCollectionandGetFiles, or MVC controllers (section 8), which do bind lists. HttpRequest.ReadFormAsync()gives you everything at once. CheckHasFormContentTypefirst, because it throws for non-form requests.
4. Saving uploads safely
An upload is untrusted input that ends up on your disk. The rules:
- Don't use the client's file name as a path. It can contain
../, absolute paths or names reserved on Windows (CON,NUL). Generate your own name. - Allow a short list of extensions and check the content, not the
Content-Typeheader. The client can send anything in both. - Limit the size.
- Store files outside the web root (not in
wwwroot), so an uploaded.htmlor.jsfile can never be served as part of your site.
using System.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
var app = builder.Build();
string uploadDir = Path.Combine(Path.GetTempPath(), "uploads-demo");
Directory.CreateDirectory(uploadDir);
const long MaxFileSize = 1 * 1024 * 1024; // 1 MB
// File signatures ("magic numbers") of allowed types
var signatures = new Dictionary<string, byte[][]>
{
[".png"] = [[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]],
[".jpg"] = [[0xFF, 0xD8, 0xFF]],
[".pdf"] = [[0x25, 0x50, 0x44, 0x46, 0x2D]], // %PDF-
};
app.MapPost("/avatar", async (IFormFile file) =>
{
if (file.Length == 0)
return Results.BadRequest("empty file");
if (file.Length > MaxFileSize)
return Results.BadRequest($"file too large: {file.Length} bytes");
// Never trust the client's file name: use it only for the extension
string ext = Path.GetExtension(file.FileName).ToLowerInvariant();
if (ext == ".jpeg") ext = ".jpg";
if (!signatures.TryGetValue(ext, out var magic))
return Results.BadRequest($"extension '{ext}' not allowed");
// Check the first bytes of the content, not the Content-Type header
await using (var s = file.OpenReadStream())
{
var header = new byte[8];
int n = await s.ReadAtLeastAsync(header, header.Length, throwOnEndOfStream: false);
if (!magic.Any(m => n >= m.Length && header.AsSpan(0, m.Length).SequenceEqual(m)))
return Results.BadRequest($"content does not look like {ext}");
}
// Our own file name, inside our own directory
string storedName = $"{Guid.NewGuid():N}{ext}";
string fullPath = Path.Combine(uploadDir, storedName);
await using (var target = File.Create(fullPath))
{
await file.CopyToAsync(target);
}
return Results.Ok(new { original = file.FileName, stored = storedName, size = file.Length });
}).DisableAntiforgery();
const string baseUrl = "http://localhost:5419";
app.Urls.Add(baseUrl);
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
async Task Upload(string fileName, byte[] bytes, string contentType)
{
using var form = new MultipartFormDataContent();
var part = new ByteArrayContent(bytes);
part.Headers.ContentType = new MediaTypeHeaderValue(contentType);
form.Add(part, "file", fileName);
var resp = await http.PostAsync("/avatar", form);
Console.WriteLine($"{fileName,-22} {(int)resp.StatusCode} {await resp.Content.ReadAsStringAsync()}");
}
byte[] png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 13];
await Upload("me.png", png, "image/png");
await Upload("../../etc/passwd.png", png, "image/png");
await Upload("script.png", "<script>alert(1)</script>"u8.ToArray(), "image/png");
await Upload("tool.exe", [0x4D, 0x5A, 0x90, 0x00], "image/png");
await Upload("big.jpg", new byte[2 * 1024 * 1024], "image/jpeg");
await Upload("empty.pdf", [], "application/pdf");
Console.WriteLine($"files on disk: {Directory.GetFiles(uploadDir).Length}");
Directory.Delete(uploadDir, recursive: true);
await app.StopAsync();
Output:
me.png 200 {"original":"me.png","stored":"df10ee52cb5840b69184e9b3615e034f.png","size":12}
../../etc/passwd.png 200 {"original":"../../etc/passwd.png","stored":"c54241daeba8449f8e7276cec6b5bc33.png","size":12}
script.png 400 "content does not look like .png"
tool.exe 400 "extension '.exe' not allowed"
big.jpg 400 "file too large: 2097152 bytes"
empty.pdf 400 "empty file"
files on disk: 2
IFormFile.FileNameis exactly what the client sent,../../etc/passwd.pngincluded. ASP.NET Core does not clean it up. Here it is only used to get the extension, so it's harmless.- If you do need the original name (for example to offer the file for download later), store it in a database next to your generated name, and pass it through
Path.GetFileNameand a character allowlist before showing it anywhere. - Checking the first bytes ("magic numbers") stops simple mistakes and renamed files. It doesn't prove a file is safe. A file can start with a valid PNG header and still be malicious. To be sure an image is an image, decode it and re-encode it (see Images). For files from the public internet, scan them with an antivirus before using them.
- The size check in the handler runs only after the whole request has been received. The limits in the next section stop large requests while they are being read.
5. Request size limits
There are two separate limits:
- Kestrel
MaxRequestBodySize: the whole request body. Default 30,000,000 bytes (about 28.6 MB). Exceeding it returns413 Payload Too Large. FormOptions.MultipartBodyLengthLimit: the multipart body when parsing a form. Default 128 MB. Exceeding it makes form reading fail with400 Bad Request.
Both can be changed globally and per endpoint:
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
// Global limits (these are the defaults, shown for reference)
builder.WebHost.ConfigureKestrel(k => k.Limits.MaxRequestBodySize = 30_000_000);
builder.Services.Configure<FormOptions>(o => o.MultipartBodyLengthLimit = 128 * 1024 * 1024);
var app = builder.Build();
string Describe(IFormFile file) => $"ok, got {file.Length:N0} bytes";
// Default limits: whole request up to ~28.6 MB
app.MapPost("/default", (IFormFile file) => Describe(file)).DisableAntiforgery();
// Whole request body limited to 100 KB for this endpoint
app.MapPost("/small", [RequestSizeLimit(100_000)] (IFormFile file) => Describe(file))
.DisableAntiforgery();
// Only the multipart body (all parts) limited to 50 KB
app.MapPost("/form-limit", (IFormFile file) => Describe(file))
.WithFormOptions(multipartBodyLengthLimit: 50_000)
.DisableAntiforgery();
// No request size limit at all (for e.g. video uploads; use with care)
app.MapPost("/unlimited", [DisableRequestSizeLimit] (IFormFile file) => Describe(file))
.WithFormOptions(multipartBodyLengthLimit: long.MaxValue)
.DisableAntiforgery();
const string baseUrl = "http://localhost:5420";
app.Urls.Add(baseUrl);
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
async Task Upload(string path, int size)
{
using var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(new byte[size]), "file", "data.bin");
try
{
var resp = await http.PostAsync(path, form);
Console.WriteLine($"{path,-11} {size,12:N0} B -> {(int)resp.StatusCode} {await resp.Content.ReadAsStringAsync()}");
}
catch (HttpRequestException e)
{
Console.WriteLine($"{path,-11} {size,12:N0} B -> {e.GetType().Name}: {e.Message}");
}
}
await Upload("/default", 1_000_000);
await Upload("/default", 40_000_000);
await Upload("/small", 80_000);
await Upload("/small", 200_000);
await Upload("/form-limit", 40_000);
await Upload("/form-limit", 60_000);
await Upload("/unlimited", 40_000_000);
await app.StopAsync();
Output:
/default 1,000,000 B -> 200 ok, got 1,000,000 bytes
/default 40,000,000 B -> HttpRequestException: An error occurred while sending the request.
/small 80,000 B -> 200 ok, got 80,000 bytes
/small 200,000 B -> 413
/form-limit 40,000 B -> 200 ok, got 40,000 bytes
/form-limit 60,000 B -> 400
/unlimited 40,000,000 B -> 200 ok, got 40,000,000 bytes
[RequestSizeLimit(n)]and[DisableRequestSizeLimit]can be put on a minimal API lambda or on an MVC action..WithFormOptions(...)(minimal APIs) and[RequestFormLimits](MVC) change the form limits per endpoint.- To accept a request bigger than 128 MB through
IFormFile, raise both limits, as/unlimiteddoes. - The client sent
Content-Length: 40000000to/default, so Kestrel knew right away that the body is too big. It sent a 413 and closed the connection while the client was still uploading, soHttpClientsaw a broken connection instead of the 413. Browsers often behave the same way. Show the user the maximum size up front, and check the size in JavaScript before uploading. FormOptionshas more limits:ValueCountLimit(1024 form fields),ValueLengthLimit(4 MB per field),MultipartHeadersLengthLimit(16 KB of headers per part) andMemoryBufferThreshold(64 KB, the size above which a part is buffered to disk).- IIS and reverse proxies have their own limits too (IIS:
maxAllowedContentLength, 30,000,000 bytes by default; nginx:client_max_body_size, 1 MB by default).
6. Streaming large files with MultipartReader
With IFormFile, a 2 GB upload is first written to a temporary file and then copied to its final place. With MultipartReader you get each part as a stream as it arrives, so you can write it straight to its destination (a file, blob storage), hash it, or reject it early.
On the client, StreamContent sends a file from disk without loading it into memory. Wrapping the stream lets you report progress:
using System.Security.Cryptography;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
var app = builder.Build();
string uploadDir = Path.Combine(Path.GetTempPath(), "stream-uploads-demo");
Directory.CreateDirectory(uploadDir);
// Handler reads the multipart body section by section, nothing is buffered
app.MapPost("/stream", async (HttpRequest request) =>
{
if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaType) ||
!mediaType.MediaType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
return Results.BadRequest("expected multipart/form-data");
string boundary = HeaderUtilities.RemoveQuotes(mediaType.Boundary).Value!;
var reader = new MultipartReader(boundary, request.Body);
var results = new List<string>();
MultipartSection? section;
while ((section = await reader.ReadNextSectionAsync()) != null)
{
if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var cd))
continue;
if (cd.IsFileDisposition())
{
string stored = Path.Combine(uploadDir, Path.GetRandomFileName());
await using var target = File.Create(stored);
using var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
var buffer = new byte[81920];
long total = 0;
int n;
while ((n = await section.Body.ReadAsync(buffer)) > 0)
{
sha.AppendData(buffer, 0, n);
await target.WriteAsync(buffer.AsMemory(0, n));
total += n;
}
string hash = Convert.ToHexStringLower(sha.GetHashAndReset());
results.Add($"file {cd.FileName.Value}: {total:N0} bytes, sha256 {hash[..16]}...");
}
else if (cd.IsFormDisposition())
{
using var sr = new StreamReader(section.Body);
results.Add($"field {cd.Name.Value} = {await sr.ReadToEndAsync()}");
}
}
return Results.Text(string.Join("\n", results));
});
const string baseUrl = "http://localhost:5421";
app.Urls.Add(baseUrl);
await app.StartAsync();
// Client: create a 5 MB file and stream it from disk
string localFile = Path.Combine(Path.GetTempPath(), "big-upload.bin");
var data = new byte[5 * 1024 * 1024];
Random.Shared.NextBytes(data);
await File.WriteAllBytesAsync(localFile, data);
Console.WriteLine($"local sha256 {Convert.ToHexStringLower(SHA256.HashData(data))[..16]}...");
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
await using (var fs = File.OpenRead(localFile))
{
using var form = new MultipartFormDataContent();
form.Add(new StringContent("nightly backup"), "description");
long lastReported = -1;
form.Add(new StreamContent(new ProgressStream(fs, sent =>
{
long pct = sent * 100 / fs.Length;
if (pct % 25 == 0 && pct != lastReported) { lastReported = pct; Console.WriteLine($" sent {pct}%"); }
})), "file", "big-upload.bin");
var resp = await http.PostAsync("/stream", form);
Console.WriteLine($"{(int)resp.StatusCode}\n{await resp.Content.ReadAsStringAsync()}");
}
File.Delete(localFile);
Directory.Delete(uploadDir, recursive: true);
await app.StopAsync();
// Read-only stream wrapper that reports how many bytes were read so far
class ProgressStream(Stream inner, Action<long> report) : Stream
{
long _read;
public override int Read(byte[] buffer, int offset, int count) =>
Track(inner.Read(buffer, offset, count));
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken ct = default) =>
Track(await inner.ReadAsync(buffer, ct));
int Track(int n) { _read += n; if (n > 0) report(_read); return n; }
public override bool CanRead => true;
public override bool CanSeek => inner.CanSeek;
public override bool CanWrite => false;
public override long Length => inner.Length;
public override long Position { get => inner.Position; set => inner.Position = value; }
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin);
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
Output:
local sha256 9bf45860d8702916...
sent 25%
sent 50%
sent 75%
sent 100%
200
field description = nightly backup
file big-upload.bin: 5,242,880 bytes, sha256 9bf45860d8702916...
- The handler takes
HttpRequestand nothing bound from the form, so the framework doesn't read the body and there is no antiforgery metadata. If you also want antiforgery for such an endpoint, callIAntiforgery.ValidateRequestAsyncyourself. - Process the sections in the order they arrive. You can't go back to an earlier section, so if a field like
descriptiondecides what to do with the file, the client must send it before the file. MultipartReaderhas its own limits:HeadersLengthLimit(16 KB) andBodyLengthLimit(no limit by default). Kestrel'sMaxRequestBodySizestill applies, so add[DisableRequestSizeLimit]or[RequestSizeLimit(...)]for big uploads.MediaTypeHeaderValue,ContentDispositionHeaderValueandHeaderUtilitiescome fromMicrosoft.Net.Http.Headers(notSystem.Net.Http.Headers).IsFileDisposition()andIsFormDisposition()are extension methods fromMicrosoft.AspNetCore.WebUtilities.StreamContentgets the length from the stream (FileStreamcan seek), so the request has aContent-Lengthheader. For a stream of unknown length it uses chunked transfer encoding.
7. Browser forms and antiforgery
A browser sends cookies with every request to your site, including a form submitted from a malicious site (CSRF). For endpoints used by browsers, keep antiforgery on: the page includes a token in a hidden field and the server checks it against a cookie:
using System.Net;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Antiforgery;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddAntiforgery();
var app = builder.Build();
app.UseAntiforgery();
app.MapGet("/", (HttpContext ctx, IAntiforgery antiforgery) =>
{
var tokens = antiforgery.GetAndStoreTokens(ctx); // also sets the antiforgery cookie
string html = $"""
<!doctype html>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="hidden" name="{tokens.FormFieldName}" value="{tokens.RequestToken}">
<input type="file" name="file" accept=".txt,.csv">
<button>Upload</button>
</form>
""";
return Results.Content(html, "text/html");
});
// Antiforgery is validated automatically for endpoints that bind form data
app.MapPost("/upload", (IFormFile file) => $"uploaded {file.FileName} ({file.Length} bytes)");
const string baseUrl = "http://localhost:5423";
app.Urls.Add(baseUrl);
await app.StartAsync();
// Simulate a browser: load the page (gets cookie + token), then submit the form
using var browser = new HttpClient(new HttpClientHandler { CookieContainer = new CookieContainer() })
{ BaseAddress = new Uri(baseUrl) };
string page = await browser.GetStringAsync("/");
var m = Regex.Match(page, "name=\"(?<n>[^\"]+)\" value=\"(?<v>[^\"]+)\"");
async Task Submit(bool withToken)
{
using var form = new MultipartFormDataContent();
if (withToken) form.Add(new StringContent(m.Groups["v"].Value), m.Groups["n"].Value);
form.Add(new StringContent("some text"), "file", "notes.txt");
var resp = await browser.PostAsync("/upload", form);
Console.WriteLine($"token={withToken}: {(int)resp.StatusCode} {await resp.Content.ReadAsStringAsync()}");
}
Console.WriteLine($"form field: {m.Groups["n"].Value}");
await Submit(withToken: true);
await Submit(withToken: false);
await app.StopAsync();
Output:
form field: __RequestVerificationToken
token=True: 200 uploaded notes.txt (9 bytes)
token=False: 400
- With
AddAntiforgery()andUseAntiforgery(), minimal API endpoints that bind form data validate the token automatically. A missing or wrong token gives400. - The form must use
method="post"andenctype="multipart/form-data". Without theenctype, the browser sends only the file names, not the files. accept=".txt,.csv"only filters the browser's file picker. It's a convenience for users, not a security check.- When you upload from JavaScript with
fetchandFormData, add the token to theFormData(or send it in theRequestVerificationTokenheader). Don't set theContent-Typeheader yourself, so the browser can add the boundary. - For more about cookies and their
SameSitesetting, which also protects against CSRF, see Cookies.
8. Uploads in MVC controllers
In controllers, List<IFormFile> properties are bound by name, and limits are set with attributes:
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
const string baseUrl = "http://localhost:5424";
app.Urls.Add(baseUrl);
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
MultipartFormDataContent NewForm(bool withPhotos)
{
var form = new MultipartFormDataContent();
form.Add(new StringContent("Holidays"), "Title");
if (withPhotos)
{
form.Add(new ByteArrayContent(new byte[1000]), "Photos", "beach.jpg");
form.Add(new ByteArrayContent(new byte[2000]), "Photos", "sunset.jpg");
}
return form;
}
foreach (bool withPhotos in new[] { true, false })
{
using var form = NewForm(withPhotos);
var resp = await http.PostAsync("/api/albums", form);
Console.WriteLine($"{(int)resp.StatusCode} {await resp.Content.ReadAsStringAsync()}");
}
await app.StopAsync();
public class AlbumForm
{
public string Title { get; set; } = "";
public List<IFormFile> Photos { get; set; } = [];
}
[ApiController]
[Route("api/albums")]
public class AlbumsController : ControllerBase
{
[HttpPost]
[RequestSizeLimit(10_000_000)]
[RequestFormLimits(MultipartBodyLengthLimit = 10_000_000)]
public IActionResult Create([FromForm] AlbumForm form)
{
if (form.Photos.Count == 0)
return BadRequest(new { error = "at least one photo is required" });
return Ok(new
{
form.Title,
photos = form.Photos.Select(p => new { p.FileName, p.Length }),
});
}
}
Output:
200 {"title":"Holidays","photos":[{"fileName":"beach.jpg","length":1000},{"fileName":"sunset.jpg","length":2000}]}
400 {"error":"at least one photo is required"}
- An action parameter can also be a single
IFormFile, anIFormFile[], aList<IFormFile>or anIFormFileCollection. - Controllers don't validate antiforgery tokens by default. MVC apps with views add
[ValidateAntiForgeryToken](or theAutoValidateAntiforgeryTokenAttributefilter globally).
9. Uploading the raw request body
When you upload one file and don't need any form fields, send the file as the whole body. There is no multipart parsing at all, and the request is easy to send from any tool (curl -T report.csv):
using System.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
var app = builder.Build();
string uploadDir = Path.Combine(Path.GetTempPath(), "raw-uploads-demo");
Directory.CreateDirectory(uploadDir);
// PUT /files/{name} with the file as the whole request body
app.MapPut("/files/{name}", async (string name, HttpRequest request) =>
{
// Allow only simple names like "report-2026.csv"
if (name.Length > 100 || name.Any(c => !(char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.'))
|| name.StartsWith('.'))
return Results.BadRequest("invalid file name");
string path = Path.Combine(uploadDir, name);
await using (var target = File.Create(path))
{
await request.Body.CopyToAsync(target);
}
return Results.Created($"/files/{name}",
new { name, size = new FileInfo(path).Length, contentType = request.ContentType });
});
app.MapGet("/files/{name}", (string name) =>
{
string path = Path.Combine(uploadDir, Path.GetFileName(name));
return File.Exists(path) ? Results.File(path, "application/octet-stream") : Results.NotFound();
});
const string baseUrl = "http://localhost:5422";
app.Urls.Add(baseUrl);
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
var body = new ByteArrayContent("id,amount\n1,9.99\n2,20.00\n"u8.ToArray());
body.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
var resp = await http.PutAsync("/files/report-2026.csv", body);
Console.WriteLine($"PUT {(int)resp.StatusCode} {resp.Headers.Location} {await resp.Content.ReadAsStringAsync()}");
resp = await http.PutAsync("/files/..%2F..%2Fevil.txt", new StringContent("x"));
Console.WriteLine($"PUT {(int)resp.StatusCode} {await resp.Content.ReadAsStringAsync()}");
Console.WriteLine("GET " + (await http.GetStringAsync("/files/report-2026.csv")).ReplaceLineEndings(" | "));
await app.StopAsync();
Directory.Delete(uploadDir, recursive: true);
Output:
PUT 201 /files/report-2026.csv {"name":"report-2026.csv","size":25,"contentType":"text/csv"}
PUT 400 "invalid file name"
GET id,amount | 1,9.99 | 2,20.00 |
- The file name comes from the URL here, so validate it with an allowlist of characters. The second request tried
../../evil.txt(encoded as%2Fso it stays in a single route segment) and was rejected. request.Body.CopyToAsyncstreams the body to disk without buffering it, just likeMultipartReader.- With
PUTto a fixed URL, sending the same file again overwrites it, which makes retries safe.
10. Checklist
- Small files and simple forms:
IFormFile. Large files:MultipartReaderor a raw body, plus raised request size limits. - Never build paths from
FileName. Generate your own names and store files outsidewwwroot. - Allow a short list of extensions, check the file signature, and for images decode and re-encode them.
- Set size limits as low as your use case allows, both per endpoint and in the reverse proxy.
- Keep antiforgery enabled for browser forms, disable it only for API endpoints used with tokens (see JWT).
- For downloads of a file from the client side, see Download a file from a web server. For a lower-level server without ASP.NET Core, see HTTP server with HttpListener.