skip to content

Model Binding Pipeline

How ASP.NET Core turns route values, query strings, headers, forms and JSON bodies into typed parameters and checks them. Interviewers probe silent binding failures and how bad input becomes a 400.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

25

In an ASP.NET Core 10 controller, how do you accept an uploaded file with IFormFile and save it to disk?

level: juniorimportance: must knowfreq 62%

answer

  1. multipart/form-data form
  2. parameter name matches the field name
  3. Length, FileName, ContentType, OpenReadStream
  4. CopyToAsync into a FileStream
  5. IFormFileCollection or List<IFormFile>

basics

~10 s

Post a multipart/form-data form and declare an IFormFile parameter named like the file field. Check Length, then CopyToAsync into a FileStream under a server-generated name; the file was already buffered before the action ran.

solid answer

~40 s

The client sends `multipart/form-data`, for example `<form method="post" enctype="multipart/form-data">` with `<input type="file" name="scan">`. The action declares `IFormFile scan`; the parameter name must match the field name, or you set it with `[FromForm(Name = "scan")]`. The parameter is `null` when the field is missing, and `Length` is 0 for an empty file. To save it, open a `FileStream` on a path you generate and `await scan.CopyToAsync(stream, ct)`; `OpenReadStream()` gives a read stream if you process it instead. For several files use `IFormFileCollection`, `List<IFormFile>` or `IEnumerable<IFormFile>`. By the time the action runs, model binding has already read the whole form: each file is held in memory up to 64 KB and spilled to a temporary file beyond that, so `IFormFile` is the buffered approach, fine for modest sizes.

code

csharp · 21 lines
csharp
[ApiController]
[Route("api/records")]
public class RecordsController(IOptions<UploadOptions> options) : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> Upload(IFormFileCollection scans, CancellationToken ct)
    {
        var saved = 0;
        foreach (var scan in scans)
        {
            if (scan.Length == 0) continue;
            var path = Path.Combine(options.Value.UploadRoot, Path.GetRandomFileName());
            await using var target = new FileStream(path, FileMode.CreateNew);
            await scan.CopyToAsync(target, ct);
            saved++;
        }
        return Ok(new { saved });
    }
}

public class UploadOptions { public string UploadRoot { get; set; } = ""; }

go deeper

for a junior

Recall the multipart form, an IFormFile parameter named after the field, the Length check and CopyToAsync to a generated path.

for a middle

Explain that the form is buffered before the action runs, the 64 KB memory threshold, the temp folder and which IFormFile members are client claims.

for a senior

Know when buffering stops being acceptable and plan limits, storage location and validation for uploads before they reach production.

for a principal

Decide where uploaded content lives (local disk, object storage, database) and what the upload path must guarantee for regulated documents.

## The request side A browser sends files only in a **multipart/form-data** body. In the telehealth app, a clinic uploads a scanned referral letter: ```razor <form method="post" action="/api/records" enctype="multipart/form-data"> <input type="file" name="scan" /> <input type="text" name="patientId" /> <button type="submit">Upload</button> </form> ``` Without the `enctype`, the browser sends only the file name as text and the file never arrives. ## The action side ```csharp [HttpPost("api/records")] public async Task<IActionResult> Upload(IFormFile scan, [FromForm] Guid patientId, CancellationToken ct) { if (scan is null || scan.Length == 0) return BadRequest("No file."); var path = Path.Combine(_options.Value.UploadRoot, Path.GetRandomFileName()); await using var stream = new FileStream(path, FileMode.CreateNew); await scan.CopyToAsync(stream, ct); return Created(); } ``` Key points: - **Name matching.** Binding looks for a form file whose field name equals the parameter name (`scan`). A mismatch leaves the parameter `null`; nothing throws, although a required parameter (a non-nullable `IFormFile` in a nullable-enabled project counts as required) also records a ModelState error, which `[ApiController]` turns into a 400. - **Several files.** `IFormFileCollection`, `List<IFormFile>` or `IEnumerable<IFormFile>` bind every file sent under that name; `IFormFileCollection.GetFiles("scan")` filters by name when you read `Request.Form.Files` directly. - **Inside a model.** An `IFormFile` property on a form-bound DTO binds the same way, together with ordinary form fields such as `patientId`. - **Saving.** `CopyToAsync(Stream, CancellationToken)` writes the content; `OpenReadStream()` returns a read-only stream when you want to hash, scan or forward the bytes instead. ## What IFormFile tells you | Member | Meaning | Trust it? | |---|---|---| | `Length` | bytes actually received for the file | yes, measured by the server | | `Name` | form field name (`scan`) | it is just the field name | | `FileName` | name the client claims | no; never use it as a storage path | | `ContentType` | MIME type the client claims | no; verify the content | | `ContentDisposition` | raw header of the part | no | ## Buffered, not streamed `IFormFile` is the **buffered** model. Before the action runs, MVC reads the entire form: 1. Each file part is copied into a buffer: memory up to `FormOptions.MemoryBufferThreshold` (64 KB), then a temporary file on disk. 2. Temporary files go to the folder named by the `ASPNETCORE_TEMP` environment variable, or the user's temp folder, and are deleted when the request ends. 3. Only then is your action called with `IFormFile` objects pointing at those buffers. That is why `IFormFile` is fine for documents of a few megabytes, and why very large uploads move to streaming with `MultipartReader`, where nothing is buffered before your code runs. ## Reading the form yourself An action can skip the parameter and read `Request.Form.Files`, an `IFormFileCollection`, or call `await Request.ReadFormAsync(ct)`. That is the same buffered parse, moved from model binding into your code: - `Request.Form.Files.GetFile("scan")` returns the first file sent under that field name, or `null`. - `Request.Form.Files.GetFiles("scan")` returns every file sent under that name. - When **model binding** matches files, the comparison of field name and parameter name is case-insensitive, and a file input the user left empty (zero length and no file name) is skipped rather than bound as an empty `IFormFile`. Reading the form manually is useful when the field name is only known at run time; otherwise the parameter is clearer and shows up in the endpoint's metadata. ## Common mistakes - Writing to `Path.Combine(root, scan.FileName)`: the client controls that string. - Saving under `wwwroot`, where the static files middleware would serve uploads publicly. - Calling `CopyTo` (synchronous) in a busy app instead of `CopyToAsync`. - Forgetting the size limits: by default Kestrel stops a request body at 30,000,000 bytes, before any of this code runs. ## Minimal APIs A Minimal API handler can take `IFormFile` or `IFormFileCollection` parameters too; how those parameters are inferred and the antiforgery check that form binding triggers there are covered with Minimal API handlers and antiforgery.

  • Why is the IFormFile parameter null even though the browser clearly sent a file?
    Usually a name mismatch: binding matches the form field name, so `<input name="file">` does not bind to a parameter called `scan`. Rename one side or use `[FromForm(Name = "file")]`. The other common cause is a form without `enctype="multipart/form-data"`, which sends no file part at all.
  • Where does a 5 MB IFormFile live while the action runs?
    In a temporary file. Form parsing buffers each file part in memory only up to `FormOptions.MemoryBufferThreshold` (64 KB) and then switches to a file in the `ASPNETCORE_TEMP` folder or the user's temp folder. That file is deleted at the end of the request, so copy it somewhere permanent inside the action.

  • IFormFile streams the upload to the action while the client is still sending it.
  • Saving to Path.Combine(uploadRoot, file.FileName) is safe because browsers send only the name.
  • IFormFile.ContentType proves what kind of file was uploaded.
  • A missing file field makes model binding throw an exception.
  • Every uploaded file is held entirely in memory until the request ends.
open as a page

In an ASP.NET Core 10 Minimal API, how do you register FluentValidation validators, run an injected IValidator<LoanApplication>, and return a ValidationProblem?

level: juniorimportance: must knowfreq 62%

basics

~10 s

Call AddValidatorsFromAssemblyContaining<LoanApplicationValidator>() at startup, inject IValidator<LoanApplication> into the handler, await ValidateAsync, and when IsValid is false return TypedResults.ValidationProblem(result.ToDictionary()), a 400 with validation problem details.

open as a page

In ASP.NET Core 10, why does a C# property named TrackingNumber come out of an API as trackingNumber, and which other JSON defaults apply?

level: juniorimportance: must knowfreq 62%

basics

~10 s

ASP.NET Core builds its System.Text.Json options from JsonSerializerDefaults.Web: property names are written in camelCase, read case-insensitively, and numbers may arrive as JSON strings. Setting PropertyNamingPolicy to null keeps the C# names.

open as a page

In an ASP.NET Core MVC controller, how do [FromRoute], [FromQuery], [FromHeader] and [FromBody] decide where a stock-adjustment action's parameters come from?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Each attribute pins a parameter to one source. [FromRoute], [FromQuery] and [FromHeader] read single named values from route data, the query string or a header; [FromBody] hands the whole request body to an input formatter, by default the System.Text.Json one.

open as a page

In ASP.NET Core MVC, how do [Required], [StringLength], [Range] and [RegularExpression] on a sign-up model feed ModelState.IsValid, and who checks it?

level: juniorimportance: must knowfreq 82%

basics

~20 s

After model binding and before the action runs, MVC evaluates every validation attribute and records failures in ModelState under the property's key. In controllers with views and in Razor Pages you check ModelState.IsValid yourself; [ApiController] returns a 400 for you.

open as a page

In ASP.NET Core 10, why does ConfigureHttpJsonOptions leave controller responses unchanged, and how do you configure JSON for both controllers and Minimal APIs?

level: middleimportance: must knowfreq 48%

basics

~10 s

Controllers and Minimal APIs read two different option types that are both named JsonOptions. AddJsonOptions configures MVC's formatters; ConfigureHttpJsonOptions configures Minimal APIs and the request/response JSON helpers. An app with both needs both calls.

open as a page

How do you serve a resumable video download from an ASP.NET Core 10 controller with PhysicalFile and range requests?

level: middleimportance: should knowfreq 40%

basics

~10 s

Return PhysicalFile(absolutePath, "video/mp4", enableRangeProcessing: true). ASP.NET Core then advertises Accept-Ranges: bytes and answers Range requests with 206 Partial Content, or 416 when unsatisfiable. Range processing is off by default.

open as a page

When an ASP.NET Core 10 app saves uploaded IFormFile documents, which values are untrusted and how should the files be stored?

level: middleimportance: should knowfreq 45%

basics

~20 s

FileName and ContentType come from the client. Store each file under a server-generated name such as Path.GetRandomFileName(), outside wwwroot, after checking size, an extension allow-list and the file signature; keep the original name only as encoded metadata.

open as a page

Why does a 150 MB upload to an ASP.NET Core 10 controller fail, and how do you raise the limits for that one action?

level: middleimportance: should knowfreq 50%

basics

~10 s

Two limits apply: the server's request body cap (Kestrel's default is 30,000,000 bytes) and FormOptions.MultipartBodyLengthLimit (128 MB per multipart section). Raise both for one action with [RequestSizeLimit(bytes)] and [RequestFormLimits(MultipartBodyLengthLimit = bytes)].

open as a page

In ASP.NET Core with FluentValidation 12, why must a validator with a MustAsync rule use ValidateAsync, and why is automatic MVC validation discouraged?

level: middleimportance: should knowfreq 48%

basics

~10 s

Calling Validate on a validator with async rules throws AsyncValidatorInvokedSynchronouslyException, so it must be awaited with ValidateAsync. MVC's validation pipeline is synchronous and MVC-only, so FluentValidation's docs advise calling validators explicitly instead of auto-validation.

open as a page

In an ASP.NET Core 10 API, how do you send and accept enum values as names such as "Zpl" instead of numbers?

level: middleimportance: should knowfreq 52%

basics

~10 s

Enums serialize as numbers by default. Add JsonStringEnumConverter to the JSON options of each stack, or put [JsonConverter(typeof(JsonStringEnumConverter<LabelFormat>))] on the enum; pass a naming policy for camelCase names and allowIntegerValues: false to reject numbers.

open as a page

Why does returning an EF Core entity with back-references from an ASP.NET Core 10 controller throw a JsonException, and how do you fix it?

level: middleimportance: should knowfreq 45%

basics

~10 s

System.Text.Json follows navigation properties, so Shipment.Parcels[0].Shipment loops until the depth limit (32 in MVC) and throws a JsonException. Return a DTO without back-references, or set ReferenceHandler.IgnoreCycles or Preserve in the JSON options.

open as a page

In an ASP.NET Core MVC action, when would you inject a dependency with [FromServices] or [FromKeyedServices] instead of the controller constructor?

level: middleimportance: should knowfreq 45%

basics

~20 s

Use them when only one action needs a dependency: the service is resolved from the request's scope for that action alone, and [FromKeyedServices("key")] picks one keyed registration. Dependencies every action uses still belong in the constructor.

open as a page

In ASP.NET Core MVC, why can only one action parameter be bound with [FromBody], and how do you accept a batch plus extra metadata?

level: middleimportance: should knowfreq 55%

basics

~20 s

An input formatter reads the whole request body stream for one parameter, so a second [FromBody] parameter has nothing left to read. Wrap both payloads in one envelope type, or move scalar metadata to the route, query string or headers.

open as a page

In ASP.NET Core MVC views, how do DataAnnotations become client-side validation rules, and what does a custom ValidationAttribute need to join them?

level: middleimportance: should knowfreq 35%

basics

~20 s

MVC maps each built-in attribute to an adapter that renders data-val-* HTML attributes on the input, and jQuery Validation Unobtrusive enforces them in the browser. A custom attribute must implement IClientModelValidator and ship a matching JavaScript rule.

open as a page

In an ASP.NET Core MVC model, when would you write a custom ValidationAttribute and when implement IValidatableObject for a cross-field sign-up rule?

level: middleimportance: should knowfreq 50%

basics

~20 s

Write a ValidationAttribute for a rule you reuse on many properties; implement IValidatableObject for a rule that compares fields of one class, such as under-18 members needing a guardian. MVC runs IValidatableObject only after the property attributes pass.

open as a page

In ASP.NET Core MVC, why does [Required] on a non-nullable int never fail, while a non-nullable string property fails with no attribute at all?

level: middleimportance: should knowfreq 52%

basics

~20 s

[Required] only detects null, and an int is never null, so a missing value becomes 0 and passes. With nullable reference types enabled, MVC treats a non-nullable string as [Required(AllowEmptyStrings = true)], and empty strings bind as null, so it fails.

open as a page

How do you stream a 200 MB multipart upload in ASP.NET Core 10 with MultipartReader instead of buffering it through IFormFile?

level: seniorimportance: should knowfreq 30%

basics

~10 s

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

open as a page

In ASP.NET Core 10 Minimal APIs, how would you run IValidator<T> for a group of loan endpoints with a reusable filter, and how does that compare with built-in AddValidation?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Write a generic IEndpointFilter that takes IValidator<T>, finds the T argument in context.Arguments, awaits ValidateAsync and returns TypedResults.ValidationProblem on failure, otherwise calls next. ASP.NET Core 10's AddValidation validates DataAnnotations and IValidatableObject, not FluentValidation rules.

open as a page

With FluentValidation's AddValidatorsFromAssemblyContaining in ASP.NET Core, what lifetime do validators get, and what breaks if you register them as singletons?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Validators are registered scoped by default. Registering them as singletons is safe only if they depend on nothing scoped; a singleton validator that takes a DbContext or a scoped credit-bureau client captures one instance for the whole app.

open as a page

In ASP.NET Core 10, how do you build a JSON Patch endpoint, and why is AddNewtonsoftJson no longer the default route to it?

level: seniorimportance: should knowfreq 32%

basics

~10 s

ASP.NET Core 10 adds Microsoft.AspNetCore.JsonPatch.SystemTextJson: bind a JsonPatchDocument<T> and call ApplyTo with an error callback. The older Microsoft.AspNetCore.JsonPatch is Newtonsoft-based and was usually wired with AddNewtonsoftJson, which replaces System.Text.Json formatters across the app.

open as a page

A legacy partner calls an ASP.NET Core 10 controller API with XML only; how do you support it, and when does the partner get 406 or 415?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Call AddXmlSerializerFormatters on AddControllers, then mark the partner's actions [Consumes("application/xml")] and [Produces("application/xml")]. A mismatched Content-Type gets 415; an unsatisfiable Accept gets 406 only when MvcOptions.ReturnHttpNotAcceptable is true, otherwise the response falls back to a default format.

open as a page

In ASP.NET Core MVC, how do [Bind] and [BindNever] stop over-posting on a form post, and why do they not protect a [FromBody] JSON payload?

level: seniorimportance: should knowfreq 50%

basics

~20 s

[Bind("Sku,Quantity")] limits which properties model binding may set, and [BindNever] removes one property from binding. Both act only on value-provider binding (form, route, query); a JSON body goes through an input formatter that ignores them.

open as a page

In ASP.NET Core MVC, when is a custom IModelBinder with an IModelBinderProvider justified, and how do you register it so it runs before the built-in binders?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Write one when a value cannot be produced by a TypeConverter or IParsable<T>.TryParse, such as a comma-separated list or a value assembled from several inputs. Register its provider with MvcOptions.ModelBinderProviders.Insert(0, ...), because the first provider returning a binder wins.

open as a page

In an ASP.NET Core [ApiController], how do you customise the automatic invalid-ModelState response with InvalidModelStateResponseFactory, and what can that factory not change?

level: seniorimportance: should knowfreq 42%

basics

~10 s

Set ApiBehaviorOptions.InvalidModelStateResponseFactory through AddControllers().ConfigureApiBehaviorOptions; it receives the ActionContext and returns the IActionResult sent instead of running the action. It only affects [ApiController] controllers and runs before your ordinary action filters.

open as a page