liveBook · Manning

Route template

As explained in .NET in Action, Second Edition

A route template is a URL pattern containing segments and parameters that ASP.NET Core uses to match requests to endpoint actions.

A route template is the string parameter of an ASP.NET Core HTTP attribute. It describes URL segments that help select an endpoint action after the controller segment has matched. section 5.4.1

For a single-resource GET endpoint:

  • Use [HttpGet("{id}")] to declare one route segment named id. section 5.4.1
  • Let ASP.NET Core combine the controller route, such as catalog, with the template to distinguish actions. section 5.4.1
  • Bind the route value to an action parameter such as int id. section 5.4.1

Requesting one book

The route [HttpGet("{id}")] on GetBook(int id) allows https://localhost:<port>/catalog/1 to select the single-book action rather than the list action. section 5.4.1

Listing 5.27 HTTP GET method to request a single Book object by id
[HttpGet("{id}")]                                 #1
public Task<Book?> GetBook(int id)                #2
{
  return _dbContext.Books.FirstOrDefaultAsync(    #3
    b => b.Id == id);
}

Inspect the focused controller listing that implements a single-resource route with an id parameter. section 5.4.1

How .NET in Action, Second Edition covers it

How deep it goes
Explains controller and segment matching with a single parameter, but defers detailed route-template rules to documentation.
Examples
Uses CatalogController, [HttpGet("{id}")], GetBook(int id), and the /catalog/1 request.
What it assumes
Assumes familiarity with controllers, action methods, URLs, and HTTP verbs while teaching single-segment route parameters.
What you can do after
Apply it via ASP.NET Core attributes to distinguish collection and single-resource GET endpoints.
How it connects
Connects URL routing with ASP.NET Core controllers, controller actions, HTTP GET, and model binding.

Also explained in

Compare how 2 books explain route template →

Related concepts

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