Skip to content
Tutorials Center
My learning

Topics

Lesson 136 of 182 ยท ASP.NET Core

Routing and Model Binding

Understand ASP.NET Core routing and model binding - route templates, constraints, optional and catch-all segments, query, header, body and form binding, AsParameters, TryParse and BindAsync.

Two questions decide what happens to every HTTP request in ASP.NET Core. Routing asks: which endpoint should handle this URL and HTTP method? Model binding asks: how do I turn the raw request (URL pieces, query string, headers, body, form fields) into the C# values the handler needs?

Both are mostly automatic, and for simple APIs you never think about them. But the moment you need an optional segment, a number that must be positive, a list in the query string, a custom type as a parameter, or a clear error when something is wrong, it pays to know the rules. This lesson gives you the full model, with a runnable server in every example (see the ASP.NET Core Overview for the setup) and the Minimal APIs lesson for the basics.

Everything here applies to minimal APIs. MVC controllers use the same routing system and an almost identical binding system, with attributes such as [HttpGet("...")] and [ApiController].

Route templates

A route template is a URL pattern made of literal text and . Each segment of the request path is matched against the corresponding segment of the template:

Template Matches Does not match
/hello /hello /hello/world
/users/{id} /users/7, /users/ada /users, /users/7/orders
/files/{name}.{ext} /files/report.pdf /files/report
/blog/{year}/{slug} /blog/2026/hello-world /blog/2026

Matching ignores letter case for literals (/Hello matches /hello) and also the query string (?a=1 is never part of route matching). The HTTP method matters too: MapGet("/users/{id}") and MapDelete("/users/{id}") are separate endpoints on the same URL.

If two templates could match one request, ASP.NET Core picks the most specific one: a literal segment beats a parameter, and a constrained parameter beats an unconstrained one. When it cannot decide, it throws an AmbiguousMatchException (HTTP 500), which you should treat as a bug in your routes.

C# Literal segments beat parameters

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.

/users/me is served by the literal route even though /users/{id} would match too. The two last paths match nothing and give 404.

Route constraints

A constraint restricts what a placeholder may match: {id:int}. If the value does not satisfy it, the route does not match at all (so the result is 404 or another route is tried). Some of the built-in constraints:

Constraint Meaning Example
int, long, double, decimal, float Parses as that type {id:int}
bool true or false {flag:bool}
guid A GUID {token:guid}
datetime A date/time {day:datetime}
alpha Letters only {code:alpha}
min(n), max(n), range(a,b) Numeric bounds {page:int:min(1)}
length(n), minlength(n), maxlength(n) String length {code:length(3)}
regex(...) Regular expression {zip:regex(^\\d{{5}}$)}
required Value must be present {slug:required}

You can chain several with colons. A regular expression in a route template needs doubled braces and backslashes, which is easy to get wrong; prefer the other constraints where possible.

C# Constraints decide whether a route matches

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 failed constraint ends as 404. That is usually what you want for a malformed URL, but note the difference from binding errors, which come later and give 400.

Optional, default and catch-all segments

  • Optional: a question mark makes a segment optional: /archive/{year?}. The handler parameter must be nullable (int? year) or have a default.
  • Default values: /greet/{name=world} supplies world when the segment is absent.
  • Catch-all: {*path} takes the rest of the URL, including slashes. {**path} does the same but keeps encoded slashes (%2F) as they are. Use it for file browsers, proxies and single-page-app fallbacks. A catch-all must be the last segment.
C# Optional, default and catch-all segments

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.

Query strings and the binding order

Parameters not found in the route are looked up in the query string (for simple types) or the body (for complex types), as the Minimal APIs lesson listed. Binding is by name, case-insensitive. Types that bind from a single string value are the simple types: all numeric types, bool, string, Guid, DateTime, DateOnly, TimeOnly, enums, and any type with a static TryParse method (more on that below).

Binding by name ignores case, but enum values must be spelled exactly as declared. Collections work too: ?tag=a&tag=b binds to string[] tag or List<string>.

C# Query string binding: simple values, lists and optional values

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 first two requests succeed. An invalid number, a missing non-nullable parameter and (surprisingly) an enum name in the wrong case such as oldest are binding failures: the framework answers 400 Bad Request before your handler runs (the body is empty because the details are only logged, with logging turned off here). To make parameters optional, make them nullable or give them a default value: int page = 1.

Always provide sensible defaults for paging and sorting (int page = 1, int pageSize = 20) and clamp the values yourself: a client asking for pageSize=1000000 is a denial-of-service attempt waiting to happen.

Headers, services and special types

The attribute [FromHeader] reads a header (underscores in the parameter name are not turned into hyphens, so supply the name: [FromHeader(Name = "X-Request-Id")]). Beyond that:

  • [FromServices] forces a parameter to come from DI. It is optional for registered types, but handy for clarity.
  • [FromKeyedServices("name")] resolves a keyed service.
  • HttpContext, HttpRequest, HttpResponse, CancellationToken, ClaimsPrincipal and Stream/PipeReader (the raw body) are special.

Explicit attributes win over inference. This is useful when the default would be wrong, for example when a complex type should come from the query string rather than the body.

Reading the body: JSON, forms and raw data

A complex type parameter on POST/PUT/PATCH is deserialised from the JSON body. Only one parameter can read the body. If the JSON is malformed or has the wrong type, the answer is 400; if the Content-Type is not JSON the answer is 415 Unsupported Media Type.

Form posts (application/x-www-form-urlencoded, multipart/form-data) are different. In .NET 8 and later, minimal APIs can bind them with [FromForm], but antiforgery validation is on by default for form binding: a request without a valid antiforgery token is rejected. Forms are mostly used for browser pages, which are covered with MVC, Razor Pages and Blazor; for APIs, JSON is the norm. To see form data without the antiforgery machinery, read it from HttpRequest.Form:

C# JSON body, form data and the raw body

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 same body stream can only be consumed once. If a middleware needs to read it as well, it has to enable buffering (request.EnableBuffering()) and rewind the stream.

Grouping parameters: [AsParameters]

Endpoints with many query parameters get unwieldy. [AsParameters] lets you collect them into one record or class. Its members are bound just like handler parameters (route, query, header, services), and you can reuse the type across endpoints.

C# AsParameters collects many inputs into one type

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.

One record holds route data, a service, a header and three query values. The second request skips the first two matches (page 2 with a page size of 2), and shows the defaults at work.

Custom binding: TryParse, BindAsync and your own types

Suppose a URL contains a coordinate like /distance?from=59.9,10.7. You could take a string and parse it by hand in every handler, or teach the framework once. Two hooks exist, both just static methods on your type:

  • static bool TryParse(string? value, out T result) (optionally with an IFormatProvider parameter): binds from a single string (route, query or header).
  • static ValueTask<T?> BindAsync(HttpContext context) (optionally with a ParameterInfo): full control, for example to combine several sources.
C# TryParse and BindAsync

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.

GeoPoint is now usable as a parameter type everywhere, with failed parsing reported as 400. CallerInfo combines two sources into one object. Design tip: TryParse is for scalar-like values; use BindAsync when you need the whole HttpContext.

Do not parse numbers with the current culture inside TryParse; the framework's own simple types use the invariant culture, and yours should behave the same (double.TryParse(text, CultureInfo.InvariantCulture, out ...)). We left that out above to keep the example short, which is fine here because the sandbox is invariant, but on a server with a German culture "59.9" could fail to parse.

Because routes have names (.WithName("GetBook")), you can build URLs from route values instead of concatenating strings. LinkGenerator is the service that does it:

C# LinkGenerator builds URLs from route names

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.

Values that are not part of the template (format) are appended as query-string parameters. If you later change the template to /catalog/b/{id}, every generated link is still correct.

Debugging routing problems

  • 404 when you expect a match? Check the HTTP method, constraints, and whether a group prefix is applied.
  • 400 before your code runs? Look at the log: it says which parameter failed and why. Turn logging on while developing.
  • 500 AmbiguousMatchException? Two endpoints match equally well: add a literal segment, a constraint or a different method.
  • See all routes. The example in Minimal APIs printed RouteEndpoint.RoutePattern.RawText for every endpoint; dotnet run in Development also supports OpenAPI documents that list them.
  • Order is not a tie-breaker. Unlike middleware, endpoint registration order does not decide between equally specific routes; specificity does.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A route is /orders/{id:int} and the request is /orders/abc. What happens?

    Constraints take part in route matching. A failed constraint means the endpoint is not selected at all, which gives 404 when nothing else matches.
  2. 2. Which template captures guide/setup/windows from /docs/guide/setup/windows in a single parameter?

    A catch-all placeholder starting with * captures the rest of the path, including slashes. It must be the last segment.
  3. 3. A handler has (string q, int page) for GET /search. The request is /search?q=cat&page=two. What is the result?

    Query values are bound after routing. A value that cannot be converted is a binding failure and produces 400 before the handler is called.
  4. 4. What is [AsParameters] for?

    A record or class marked with [AsParameters] has its constructor parameters or properties bound as if they were separate handler parameters.
  5. 5. How do you let a custom type such as GeoPoint be bound from a query string value?

    The binder looks for a static TryParse method on the parameter type. For full control over all request data, a static BindAsync(HttpContext) method works too.

Summary

  • A route template mixes literals and ; the most specific match wins, case is ignored and the HTTP method is part of the match.
  • Constraints (:int, :guid, :min(1), :length(3)) are part of matching: failing one gives 404. Binding failures (missing or unparseable values) give 400.
  • Segments can be optional ({id?}), have defaults ({name=world}) or catch the rest of the path ({*path}).
  • Parameters come from route, query, headers, services, special types, or the JSON body; attributes such as [FromQuery] and [FromHeader] override the defaults.
  • [AsParameters] groups inputs into one type; static TryParse and BindAsync teach the framework to bind your own types.
  • Name endpoints and use LinkGenerator to build links; read the logs when binding or routing surprises you.

Next: Middleware and the Request Pipeline