Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 52 ยท Routing and Minimal APIs

Parameter Binding in Minimal APIs

How minimal API handlers get their arguments: route, query, header, body, form and service binding, AsParameters, special types and what happens on failure.

An endpoint handler is just a delegate, and its parameters are the inputs it needs. You never write code that reads the URL or parses JSON. Instead you declare what you want (int id, string? search, CreateTodo body, ITodoStore store) and ASP.NET Core fills each parameter before your code runs. This is called parameter binding, and understanding its rules makes handlers short and predictable, and explains almost every mysterious 400 Bad Request you will see.

In this lesson you will learn where each parameter's value comes from, how to override the default, how to bundle many parameters into one object with [AsParameters], which special types are provided by the framework, and what happens when binding fails.

Where does a parameter come from?

For each parameter the framework picks a binding source by following a fixed list of rules, in this order:

  1. An explicit attribute ([FromRoute], [FromQuery], [FromHeader], [FromBody], [FromForm], [FromServices]) wins.
  2. A parameter of a special type (HttpContext, HttpRequest, HttpResponse, CancellationToken, ClaimsPrincipal, Stream, PipeReader) is provided by the framework.
  3. A parameter whose name appears in the route template, such as , comes from the route.
  4. A type registered in the dependency injection container, or marked with [FromServices], is injected.
  5. A simple type (string, numbers, bool, Guid, DateTime, enums and any type with a static TryParse) comes from the query string.
  6. Any other type (a class or record) is read from the JSON request body.
flowchart TD
    P["Handler parameter"] --> A{"Has a [From...]<br/>attribute?"}
    A -- yes --> S1["Use that source"]
    A -- no --> B{"Special framework type?"}
    B -- yes --> S2["HttpContext, CancellationToken, ..."]
    B -- no --> C{"Name in route template?"}
    C -- yes --> S3["Route value"]
    C -- no --> D{"Registered service?"}
    D -- yes --> S4["Dependency injection"]
    D -- no --> E{"Simple type?"}
    E -- yes --> S5["Query string"]
    E -- no --> S6["JSON body"]

The binding decision for one parameter, simplified. The first matching rule wins.

Route, query and header values

The three most common sources are all strings on the wire, so the framework converts them to your parameter type. A conversion failure means a 400.

C# Route, query and header binding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at the details, because each one is a rule you will meet again:

  • string? search is optional because it is nullable. A plain string search would be required; leaving it out gives a 400.
  • int page and int pageSize are not nullable, but the first request still supplied them. If you left page out, binding would fail with 400. For optional numbers use int? page or a default value in a lambda parameter (int page = 1; this works for lambdas, local functions and method handlers).
  • [FromQuery(Name = "page-size")] and [FromHeader(Name = "X-Client")] bind to names that are not valid C# identifiers. The attributes live in Microsoft.AspNetCore.Mvc, so add that using (the web SDK's implicit usings do not include it).
  • Enums, bool and Guid are parsed from text. Enum names must match exactly (day=friday is a 400 here, while day=Friday and the number day=5 both work), and verbose=maybe is not a bool. Optional Guid? token is simply none when absent.
  • Route constraints such as {id:int} are checked by routing before binding; /books/abc would not match this endpoint at all and returns 404.

Defaults and optional values

You can make query parameters tolerant by giving them defaults. A lambda with a default value is supported since C# 12.

C# Optional parameters with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last two requests fail with 400: the first because required q is missing, the second because two cannot be converted to int. Your handler does not run at all in either case, so you never need to null-check a required parameter.

The request body and services

A complex type with no other explanation is read from the body as JSON, using the same System.Text.Json web defaults you will meet in JSON Serialization in APIs. A handler can have only one body parameter, because a body can be read only once. Services registered in the container are injected, and CancellationToken is tied to the client's connection: it is cancelled when the client disconnects.

C# Body, services and special types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both ids are 1 and 2 because the IdGenerator singleton is shared by all requests. The three failures return 400 for a missing body and malformed JSON and 415 Unsupported Media Type for the wrong content type; the exact message is only logged, not sent, which is why a global error strategy (Error Handling and Problem Details) matters in a real API.

A body is inferred only for methods that normally carry one (POST, PUT, PATCH). A complex-typed parameter in a GET or DELETE handler is not inferred as a body: the endpoint fails when it is built, with a message suggesting [FromServices] or [FromBody]. To read many query values into one object, use [AsParameters] (below). A GET with a body is unusual and many proxies drop it, so avoid it.

Binding many values with [AsParameters]

A search endpoint can easily take ten query values. Declaring ten lambda parameters is noisy, and you want to reuse them. [AsParameters] tells the framework to treat a record, class or struct as a bag of parameters: each constructor parameter or property is bound like a separate handler parameter, with its own attribute and rules.

C# [AsParameters] for a search request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Every record parameter went through the same rules as before: Shop matched the route, MaxPrice, Tag, Page and PageSize came from the query string, UserAgent from a header and Catalog was injected. The record gives the search a name, makes it easy to reuse in several endpoints and keeps the lambda to one line.

Custom binding: TryParse and BindAsync

Any type with a public static TryParse(string, out T) method counts as a simple type. That lets you accept your own formats from the route or query.

C#
record Point(double X, double Y)
{
    public static bool TryParse(string? text, out Point point)
    {
        point = default!;
        var parts = text?.Split(',');
        if (parts is not { Length: 2 }
            || !double.TryParse(parts[0], out double x)
            || !double.TryParse(parts[1], out double y))
        {
            return false;
        }
        point = new Point(x, y);
        return true;
    }
}

app.MapGet("/distance", (Point from, Point to) => Math.Sqrt(Math.Pow(to.X - from.X, 2) + Math.Pow(to.Y - from.Y, 2)));
// GET /distance?from=0,0&to=3,4  ->  5

For anything that needs the whole HttpContext (for example reading a custom header combination), add public static ValueTask<T?> BindAsync(HttpContext context). Both hooks are plain static methods on your type, so no registration is required.

When binding fails

Binding failures never reach your handler. By default they produce these statuses:

Situation Result
Required query, route or header value missing, or cannot be converted 400 Bad Request
Body missing or invalid JSON 400 Bad Request
Body sent with a wrong Content-Type 415 Unsupported Media Type
A parameter marked [FromServices] has no registration An InvalidOperationException while resolving it, which becomes a 500 response

The fix for "I need a friendlier message" is not to catch these in the handler. Accept the value as nullable and validate it yourself, or add a validation filter (Endpoint Filters, Model Validation) that returns a ProblemDetails response.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A handler is declared as (int id, string? q, UpdateDto body) for PUT /items/{id}. Where does each parameter come from?

    A name that appears in the route template binds from the route, a simple nullable type binds from the query string, and an unexplained complex type is read from the JSON body.
  2. 2. What happens if a request is missing a query value for a non-nullable parameter such as int page with no default?

    Non-nullable parameters without a default are required. Binding fails and the framework returns 400 before your code is called.
  3. 3. What does [AsParameters] do?

    [AsParameters] expands the members of a type into individual parameters, so a long list of route, query, header and service values can be reused as one object.
  4. 4. How many parameters in one handler can be bound from the request body?

    The request body is a stream that can be read once, so a handler may have only one body parameter.
  5. 5. A POST sends valid JSON but with Content-Type: text/plain. What does a minimal API return for a JSON body parameter?

    JSON body binding requires an application/json compatible content type. Otherwise the framework answers 415.

Summary

  • Parameters are bound by rule: explicit attribute, special type, route name, service, simple type from the query, other types from the JSON body.
  • Nullable types and default values make a parameter optional; everything else is required and a failure returns 400 before your handler runs.
  • [FromQuery], [FromHeader], [FromRoute], [FromBody], [FromForm] and [FromServices] override the defaults and let you rename values.
  • HttpContext, HttpRequest, HttpResponse and CancellationToken are provided by the framework; services are injected.
  • [AsParameters] groups many parameters into one reusable record.
  • A static TryParse or BindAsync on your own type adds custom binding.

Next: Responses, Results and Content Negotiation