liveBook · Manning

FromRoute attribute

As explained in ASP.NET Core in Action, 3e

The FromRoute attribute is an ASP.NET Core parameter-binding attribute that specifies binding a parameter from route values.

The [FromRoute] attribute explicitly binds a minimal API handler parameter to a route value. It overrides ASP.NET Core’s default binding conventions, which can usually infer route binding when parameter and route names match. section 7.2

Bind an identifier from the route

app.MapGet("/products/{id}/paged", ([FromRoute] int id, [FromQuery] int page, [FromHeader(Name = "PageSize")] int pageSize) => $"Received id {id}, page {page}, pageSize {pageSize}"); A request such as /products/123/paged binds 123 to id. If the required route parameter is absent from the route template, application execution throws an exception at runtime. section 7.2

Listing 7.1 Binding simple values using [From] attributes
using Microsoft.AspNetCore.Mvc;                                 #1
 
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
 
app.MapGet("/products/{id}/paged",
    ([FromRoute] int id,                                        #2
     [FromQuery] int page,                                      #3
     [FromHeader(Name = "PageSize")] int pageSize)              #4
     => $"Received id {id}, page {page}, pageSize {pageSize}");
 
app.Run();

Compare explicit route, query-string, and header binding in one runnable minimal API endpoint. section 7.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains explicit binding, name requirements, runtime failure, and its place before other binding strategies.
Examples
Uses a products endpoint that binds an integer id from /products/{id}/paged alongside page and PageSize values.
What it assumes
Assumes basic minimal API endpoint and route-template knowledge while explaining binding conventions from the beginning.
What you can do after
Apply it via ASP.NET Core minimal APIs to make route-value binding explicit and distinguish it from query and header binding.
How it connects
Contrasts with model binding conventions, FromQuery, FromHeader, FromBody, FromServices, BindAsync, and TryParse.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.