File uploads

suggest change

A 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:

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--

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:


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:


4. Saving uploads safely

An upload is untrusted input that ends up on your disk. The rules:

  1. 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.
  2. Allow a short list of extensions and check the content, not the Content-Type header. The client can send anything in both.
  3. Limit the size.
  4. Store files outside the web root (not in wwwroot), so an uploaded .html or .js file 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

5. Request size limits

There are two separate limits:

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

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...

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

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"}

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 | 

10. Checklist

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents