In ASP.NET Core, what do UseRouting and UseEndpoints each do, and why does middleware placed before UseRouting get null from HttpContext.GetEndpoint()?
answer
- select first, execute later
- SetEndpoint and Request.RouteValues
- metadata readable in between
- WebApplication adds both if you don't
- UseEndpoints is terminal on a match
basics
~10 sUseRouting matches the request and stores the chosen endpoint on HttpContext; UseEndpoints runs that endpoint's delegate. Middleware before UseRouting runs before any endpoint has been selected, so GetEndpoint() returns null there.
solid answer
~40 sEndpoint routing splits dispatch in two. `UseRouting` adds the routing middleware, which matches the path, method and other policies, then calls `SetEndpoint` and fills `Request.RouteValues`. `UseEndpoints` adds the endpoint middleware, which invokes the selected endpoint's `RequestDelegate` and is terminal when one was found. Anything in between can call `HttpContext.GetEndpoint()` and read the endpoint's metadata before the handler runs; that is how `UseAuthorization` and `UseCors` apply per-endpoint policies. Middleware placed before `UseRouting` sees `null` because selection has not happened yet. In a `WebApplication`, if you never call `UseRouting`, it is added at the start of the pipeline, so your `app.Use` middleware does see the endpoint; calling `app.UseRouting()` explicitly moves it to that spot.
code
csharp · 22 linesvar app = WebApplication.CreateBuilder(args).Build();
app.Use(async (context, next) =>
{
// Before the explicit UseRouting below: always null
Console.WriteLine($"1. {context.GetEndpoint()?.DisplayName ?? "(null)"}");
await next(context);
});
app.UseRouting();
app.Use(async (context, next) =>
{
// After UseRouting: the selected endpoint, or null if nothing matched
Console.WriteLine($"2. {context.GetEndpoint()?.DisplayName ?? "(null)"}");
await next(context);
});
app.MapGet("/orders/{id:int}", (int id) => Results.Ok(new { id }))
.WithDisplayName("Get order");
app.Run();go deeper
Recall that UseRouting chooses the endpoint and UseEndpoints runs it, and that GetEndpoint() is null before routing.
Explain SetEndpoint and RouteValues, why metadata-reading middleware sits between the two, and what WebApplication adds implicitly.
Diagnose the 'contains authorization metadata' error and null endpoints caused by an explicit UseRouting placed too late, and place rewrite-style middleware before routing.
Use the select-then-execute split as the extension point for cross-cutting policy, so teams attach metadata to endpoints instead of re-parsing paths in middleware.
## Two middleware, two jobs ASP.NET Core's **endpoint routing** separates choosing a handler from running it: | Middleware | Added by | Job | |---|---|---| | `EndpointRoutingMiddleware` | `app.UseRouting()` | Match the request against every endpoint's route pattern and policies, then store the winner | | `EndpointMiddleware` | `app.UseEndpoints(...)` | Invoke the selected endpoint's `RequestDelegate` | When routing finds a match it calls `HttpContext.SetEndpoint(endpoint)` and sets `HttpContext.Request.RouteValues`. Any later code reads them back with `HttpContext.GetEndpoint()` and `Request.RouteValues`. If nothing matches, the endpoint stays `null`, the endpoint middleware has nothing to run, and the request continues down the pipeline, usually to a 404. ## Why the split exists The gap between the two is the point. Middleware placed there can see **which** endpoint will run and its **metadata** before the handler executes: - `UseAuthorization` reads `IAuthorizeData` and policy metadata from the endpoint. - `UseCors` reads the endpoint's CORS policy metadata. - Your own middleware can read a marker attribute, for example a food-delivery API flagging endpoints that require the kitchen to be open. ```csharp app.UseRouting(); app.Use(async (context, next) => { var endpoint = context.GetEndpoint(); // null before UseRouting if (endpoint?.Metadata.GetMetadata<RequiresOpenKitchenAttribute>() is not null && !KitchenClock.IsOpen()) { context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; return; } await next(context); }); app.UseAuthorization(); ``` Middleware **before** `UseRouting` cannot do this: the endpoint is still `null`. It is the right place for things that change what routing sees, such as `UseRewriter`, `UseHttpMethodOverride` or `UsePathBase`. ## What WebApplication does for you With `WebApplication` (`var app = builder.Build();`) you rarely call either method. In the v10.0.12 source, when the app has endpoints: 1. If your code never called `UseRouting`, the framework adds it **at the start** of the pipeline, after the developer exception page in Development. 2. `UseAuthentication` and `UseAuthorization` are added when their services are registered and you did not add them yourself. 3. Your own middleware runs next. 4. `UseEndpoints` is added **at the end**, so `app.MapGet(...)` endpoints run last. So in a minimal `Program.cs` every `app.Use(...)` you write already runs after routing and sees the endpoint. The moment you call `app.UseRouting()` yourself, routing runs exactly there, and any middleware above that line goes back to seeing `null`. ## Inspecting what routing chose Between the two middleware you can read more than metadata: - `context.Request.RouteValues` holds the values captured from the template, such as `id = "42"`. - Casting the endpoint to `RouteEndpoint` exposes `RoutePattern.RawText`, the template text, which is a better label for metrics and logs than the raw path because it does not explode into one entry per order id. - `Endpoint.DisplayName` gives the human-readable name used in routing's own log lines. None of these exist before routing runs, which is the practical meaning of "middleware before `UseRouting` sees no endpoint". ## Terminal behaviour The endpoint middleware is **terminal when it runs an endpoint**: middleware registered after `UseEndpoints` only runs for requests that matched nothing. In the routing docs' trace, a request to a mapped path logs the endpoint between the two middleware and never reaches the code after `UseEndpoints`, while an unmatched path reaches it with `null`. ## The error you get when the order is wrong If an endpoint carries authorization metadata but the authorization middleware ran before routing selected it, the endpoint middleware refuses to run it and throws an `InvalidOperationException`: the endpoint "contains authorization metadata, but a middleware was not found that supports authorization", adding that `app.UseAuthorization()` must go between `UseRouting` and `UseEndpoints`. The same check exists for CORS and antiforgery metadata. It is the framework telling you a policy middleware never saw the endpoint. ## What interviewers listen for - Routing **selects**, the endpoint middleware **executes**. - `GetEndpoint()` is `null` until routing runs, which is why order matters. - Metadata-driven middleware belongs between the two. - `WebApplication` adds routing first and endpoints last unless you call them yourself.
- In a WebApplication that never calls UseRouting, does app.Use middleware see the endpoint?Yes. When endpoints exist and user code did not call `UseRouting`, `WebApplication` adds it at the beginning of the pipeline, so every `app.Use` middleware runs after selection and `GetEndpoint()` returns the match. Calling `app.UseRouting()` explicitly moves routing to that line, and middleware above it then sees `null`.
- Which middleware typically belongs before UseRouting rather than after it?Middleware that changes the request routing will look at: `UseRewriter`, `UseHttpMethodOverride`, `UsePathBase`, and similar. They must run before matching, because once routing has chosen an endpoint, changing the path or method no longer affects which endpoint runs.
- What happens to middleware registered after UseEndpoints?It runs only when no endpoint matched. The endpoint middleware is terminal when it executes an endpoint, so it does not call the next middleware. That is why code after `UseEndpoints` sees a `null` endpoint in the routing docs' trace.
A restaurant host checks the reservation at the door and hands the guest a table card; waiters on the way read the card to bring the right menu, and only the kitchen cooks. A waiter standing outside the door, before the host, has no card to read.
- Says UseRouting both selects and executes the endpoint.
- Reads endpoint metadata in middleware placed before an explicit UseRouting call.
- Believes WebApplication requires calling UseRouting and UseEndpoints explicitly.
- Thinks middleware after UseEndpoints runs for every request.
- Puts UseRewriter after UseRouting and expects the rewritten path to change the match.