liveBook · Manning

Routing middleware

As explained in Pro ASP.NET Core 7, Tenth Edition

Routing middleware is an ASP.NET Core request-pipeline component that matches requests to endpoints and stores the selected endpoint for later processing.

Routing middleware matches an incoming request to an endpoint. In an explicit pipeline, `UseRouting()` selects a route; `UseEndpoints()` executes its endpoint to generate the response. Keeping those steps separate lets middleware between them inspect the selected endpoint before it runs. section 13.3.3 section 13.1.2

A route pairs a URL path pattern with an endpoint:

  • `MapGet("routing", handler)` matches GET requests for `/routing`. Other mapping methods handle POST, PUT, DELETE, specified methods, or all methods. section 13.1.2
  • `MapGet("capital/{country}", handler)` captures a path segment. The handler reads its value from `context.Request.RouteValues["country"]`. section 13.1.5
  • An endpoint can be an asynchronous `RequestDelegate` that receives `HttpContext` and writes a response. section 13.1.2

Register and test a route

After building `app` in `Program.cs`, register `app.MapGet("routing", async context => { await context.Response.WriteAsync("Request Was Routed"); });`, then call `app.Run()`. Request `http://localhost:5000/routing` to see `Request Was Routed`. `WebApplication` accepts routes directly; ASP.NET Core can apply the routing setup automatically, even though routing middleware still performs the match. section 13.1.2 section 13.1.3

Pipeline configuration is not just cosmetic. With explicit `UseRouting()` and `UseEndpoints()`, an unmatched request can continue to later middleware; a matched endpoint handles the response. When switching to direct route registration, remove or reconsider a terminal middleware component: in the demonstrated configuration it runs for every request. The C# analyzer also warns when `UseEndpoints()` is used instead of top-level route registration. section 13.1.2 section 13.1.3

Inspect the selected endpoint

Place middleware between `UseRouting()` and `UseEndpoints()`, then call `context.GetEndpoint()`. A non-null result exposes the selected endpoint’s `DisplayName`, metadata, and request delegate. `WithDisplayName()` makes the selection easier to recognize in a response or diagnostic message. Changing it with `SetEndpoint()` is possible but calls for a compelling reason. section 13.3.3

Listing 13.5 Using the routing middleware in the Program.cs file in the Platform folder
using Platform;

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.UseMiddleware<Population>();
app.UseMiddleware<Capital>();

app.UseRouting();

#pragma warning disable ASP0014

app.UseEndpoints(endpoints => {
    endpoints.MapGet("routing", async context => {
        await context.Response.WriteAsync("Request Was Routed");
    });
});

app.Run(async (context) => {
    await context.Response.WriteAsync("Terminal Middleware Reached");
});

app.Run();

See a complete `Program.cs` pipeline with explicit routing, a GET endpoint, and terminal middleware for unmatched requests. section 13.1.2

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Works through registration, path patterns, route values, and endpoint inspection; describes route scoring without detailing its algorithm.
Examples
Uses `/routing`, `/capital/uk`, three-segment paths, and a middleware response reporting the selected endpoint.
What it assumes
Assumes familiarity with C# middleware and `HttpContext`, while showing how to register routes and endpoints.
What you can do after
Build it from scratch with `MapGet`, read captured route values, and inspect the selected endpoint from middleware.
How it connects
Connects URL routing to middleware pipelines, RequestDelegate, HttpContext, route parameters, and endpoint metadata.

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 Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.