How do you stream a 200 MB multipart upload in ASP.NET Core 10 with MultipartReader instead of buffering it through IFormFile?
answer
- nothing may read the form first
- remove the form value provider factories
- Request.GetMultipartBoundary()
- ReadNextSectionAsync, AsFileSection
- BodyLengthLimit is per section, default none
basics
~10 sKeep MVC from reading the form, then create a MultipartReader over Request.Body with Request.GetMultipartBoundary(), loop ReadNextSectionAsync, and copy each AsFileSection().FileStream straight to storage. Only the server body limit and your own checks apply.
solid answer
~40 sStreaming means your code consumes `Request.Body` while it arrives. In MVC, any bound action parameter makes model binding build value providers, and `FormValueProviderFactory` then reads and buffers the whole multipart form first. So the action must bind nothing from the form: either take no bound parameters, or add a resource filter that removes `FormValueProviderFactory`, `FormFileValueProviderFactory` and `JQueryFormValueProviderFactory` from `context.ValueProviderFactories`. Inside, `new MultipartReader(Request.GetMultipartBoundary(), Request.Body)` reads sections one by one with `ReadNextSectionAsync`; `section.AsFileSection()` gives a `FileMultipartSection` whose `FileStream` you copy to disk or blob storage, and `AsFormDataSection()` gives text fields. `FormOptions` no longer applies: set `BodyLengthLimit` for each section yourself, keep `[RequestSizeLimit]` for the total, and validate size and content while you copy.
code
csharp · 12 lines// your own filter: stops MVC from parsing (and buffering) the form
public sealed class SkipFormBindingAttribute : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
context.ValueProviderFactories.RemoveType<FormValueProviderFactory>();
context.ValueProviderFactories.RemoveType<FormFileValueProviderFactory>();
context.ValueProviderFactories.RemoveType<JQueryFormValueProviderFactory>();
}
public void OnResourceExecuted(ResourceExecutedContext context) { }
}go deeper
Recall that IFormFile buffers uploads and that MultipartReader exists for reading a multipart body yourself.
Explain the section loop with ReadNextSectionAsync, AsFileSection and AsFormDataSection, and why form value providers must not run first.
Build a streaming endpoint that sets its own section limit, validates while copying, cleans up partial files, and keeps the server limit in place.
Decide when uploads should bypass the app entirely, for example direct-to-storage uploads with short-lived credentials, versus streaming through it.
## Why IFormFile is the wrong tool at 200 MB With `IFormFile`, MVC reads the whole form before the action runs and copies each file into a buffer, mostly a temporary file. A 200 MB scan is written to the temp folder once, then copied again to its real destination. Under load, that doubles disk I/O, needs temp space for every concurrent upload, and lets nothing start until the last byte arrives. **Streaming** reads the multipart body section by section and writes each file straight to its destination. ## Step 1: make sure nothing reads the form first MVC creates value providers whenever an action has bound parameters or properties. For a multipart request, `FormValueProviderFactory` and `FormFileValueProviderFactory` call `ReadFormAsync`, which buffers the entire upload. Two ways around it: 1. Give the action **no bound parameters** (read route values from `RouteData` if needed). 2. Add a **resource filter** you write that removes the three form-related factories with `context.ValueProviderFactories.RemoveType<...>()`. Resource filters run before model binding, so the form is never parsed. In a Minimal API, a handler that takes only `HttpRequest` and `CancellationToken` does not read the form. ## Step 2: read the sections ```csharp var boundary = Request.GetMultipartBoundary(); if (string.IsNullOrEmpty(boundary)) return BadRequest(); var reader = new MultipartReader(boundary, Request.Body) { BodyLengthLimit = 209_715_200 }; ``` - `GetMultipartBoundary()` (namespace `Microsoft.AspNetCore.Http.Extensions`) extracts the boundary parameter from `Content-Type`, or returns an empty string. - `ReadNextSectionAsync(ct)` returns the next `MultipartSection`, or `null` at the end. - `AsFileSection()` returns a `FileMultipartSection` with `Name`, `FileName` and `FileStream`, or `null` when the part is not a file; `AsFormDataSection()` handles ordinary fields, whose value you read with `GetValueAsync()`. ## Step 3: copy, check and limit as you go | Concern | Buffered `IFormFile` | Streaming `MultipartReader` | |---|---|---| | Per-file limit | `FormOptions.MultipartBodyLengthLimit` (128 MB) | `MultipartReader.BodyLengthLimit` (no limit unless you set one) | | Total body limit | server limit, `[RequestSizeLimit]` | the same | | Header limits | `FormOptions` | `HeadersLengthLimit` (16 KB), `HeadersCountLimit` (16) | | Temp files | yes | none | | Validation | after the fact | while copying | Write each section to a server-generated name, check the first bytes against the expected file signature before accepting more, count bytes, and delete the partial file if anything fails or the client disconnects. ## Step 4: model binding after the stream Text fields arrive as sections in whatever order the client sent them. Collect them into a dictionary while streaming and validate the resulting model yourself, because MVC's binding and validation never ran. Clients should send metadata fields before the file so the handler can authorize the patient record before it accepts 200 MB. ## Failure modes to handle - **The form was already read.** A bound parameter, a value provider or a middleware that called `ReadFormAsync` consumed the body, so the reader finds nothing left to stream. - **No boundary.** A request that is not `multipart/form-data` yields an empty boundary; reject it before constructing the reader (the example answers 400). - **A section over the limit.** Reading past `BodyLengthLimit` throws `InvalidDataException` ("Multipart body length limit ... exceeded."); catch it, delete the partial file and answer with a client error. - **The client disconnects.** Reads throw an `IOException`-based exception or, through the token, an `OperationCanceledException`; delete partial files in a `finally` block. ## Operational notes - Keep `[RequestSizeLimit]` set on the endpoint: the server limit is the only cap on the whole body. - Pass the request's `CancellationToken` to every read and write, so an aborted upload stops consuming disk. - Antiforgery for browser-posted forms still applies; how to validate it for a streaming endpoint is part of antiforgery configuration. - For cloud storage, copy the section stream into the storage client's upload stream instead of a local file.
- The streaming action takes a CancellationToken parameter and still buffers the whole upload. Why?Any bound parameter makes MVC run its binder delegate, which first creates all value providers; for a multipart request the form value provider factories call `ReadFormAsync` and buffer the body. Remove those factories with a resource filter, so the `CancellationToken` binds without touching the form.
- Does FormOptions.MultipartBodyLengthLimit protect a MultipartReader endpoint?No. `FormOptions` is read by form parsing (`ReadFormAsync`), which a streaming endpoint deliberately skips. A `MultipartReader` you create has `BodyLengthLimit` unset, meaning no per-section limit, so set it yourself; the server's request body limit, raised with `[RequestSizeLimit]`, still caps the whole body.
- An action that takes IFormFile streams the upload as long as the code uses OpenReadStream.
- FormOptions.MultipartBodyLengthLimit also limits sections read with your own MultipartReader.
- MultipartReader removes the need for any request size limit on the endpoint.
- Adding a CancellationToken parameter cannot cause the form to be buffered.
- Form fields always arrive before the file sections, so their order needs no handling.