liveBook · Manning

Routing middleware

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

UseRouting is an ASP.NET Core extension method that adds routing middleware to a web application's request pipeline.

Routing middleware selects an endpoint for an incoming request by matching its URL to a registered route. The request then continues through the middleware pipeline. Endpoint middleware executes the selected endpoint and generates the response. In ASP.NET Core, the routing component is EndpointRoutingMiddleware; `app.UseRouting()` adds it to the pipeline. section 6.2 section 4.2.3

You usually do not need to call `UseRouting()` yourself: WebApplication adds routing and endpoint middleware by default. Add it explicitly when their position matters. For example, placing routing after static-file middleware lets static-file requests be handled first; placing authorization after routing lets it act on the selected endpoint. Middleware before routing cannot yet see that selection. section 6.5 section 13.1.2

A minimal API route

`app.MapGet("/", () => "Hello World!")` registers an endpoint; it does not add middleware. For a GET request to `/`, routing selects that endpoint, and endpoint middleware runs its handler. Middleware earlier in the pipeline can instead generate a response and stop the request before it reaches routing. section 3.7.2 section 4.2.3

Listing 14.1 Registering Razor Pages in Startup.Configure
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddRazorPages();    #1
 
var app = builder.Build();
 
app.UseStaticFiles();
app.UseRouting();                    #2
app.UseAuthorization();
 
app.MapRazorPages();                 #3
 
app.Run();

In this Razor Pages pipeline, `UseRouting()` follows static files and precedes authorization. `MapRazorPages()` registers the page endpoints that routing can select. section 14.1

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

How deep it goes
Explains two-stage request handling and middleware placement, but defers detailed Razor Page handler selection.
Examples
Uses a `MapGet` Hello World endpoint and a Razor Pages pipeline ordered around static files and authorization.
What it assumes
Assumes basic familiarity with the middleware pipeline and introduces how `MapGet` defines an endpoint rather than middleware.
What you can do after
Operate/configure it with `UseRouting()` when explicit placement is needed, while leaving endpoint execution to endpoint middleware.
How it connects
Connects route templates and endpoints with endpoint middleware, static-file middleware, authorization, minimal APIs, and Razor Pages.

Also explained in

Compare how 2 books explain routing middleware →

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.