C# / .NET Compendium PLEN
.NET / C# / Web API, Blazor

Endpoint Routing in ASP.NET Core

The problem it solves - separating "route matching" from "execution"

In the older model (classic middleware routing) matching a URL to logic happened in one place, close to the handling logic itself. Endpoint Routing (the default since ASP.NET Core 3.0) splits this into two separate steps in the pipeline:

var app = builder.Build();

app.UseRouting();      // KROK 1: dopasuj URL do endpointu (ale jeszcze NIE wykonuj)
app.UseAuthentication();
app.UseAuthorization(); // runs HERE, because it already KNOWS which endpoint was matched (and its metadata)
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapGet("/health", () => "OK");
});          // KROK 2: dopiero TU faktycznie wykonaj dopasowany endpoint

Why this matters - metadata available EARLIER in the pipeline

The key advantage: middleware between UseRouting() and UseEndpoints() already knows which endpoint will be invoked, and can read its metadata (attributes such as [Authorize], [AllowAnonymous]) before it actually gets there:

[Authorize(Roles = "Admin")]
[HttpGet("admin/reports")]
public IActionResult GetReports() => Ok();

The UseAuthorization() middleware, running after UseRouting() but before UseEndpoints(), sees the [Authorize(Roles = "Admin")] attribute on the matched endpoint without executing it - it can reject the request (403) before any controller code runs. In the old model (without the split) such a check would have to be written into every action by hand, or the middleware would have to "guess" what is going to happen.

Endpoint as a first-class object

app.Use(async (context, next) =>
{
    var endpoint = context.GetEndpoint(); // available AFTER UseRouting(), before execution
    if (endpoint != null)
    {
        Console.WriteLine($"Dopasowano endpoint: {endpoint.DisplayName}");
    }
    await next();
});

Endpoint Routing represents the matched route as an object (Endpoint) with metadata, available through HttpContext.GetEndpoint() - this is the foundation on which Minimal API, routing in Blazor, gRPC and SignalR in ASP.NET Core stand - all of them use the same, shared mechanism, instead of each having its own.

Minimal API - routing without controllers

app.MapGet("/orders/{id}", (int id, IOrderService service) => service.GetOrder(id));
app.MapPost("/orders", (CreateOrderRequest req, IOrderService service) => service.CreateOrder(req));

This is the same Endpoint Routing "under the hood" - MapGet/MapPost register an endpoint with the same metadata and the same matching mechanism as [HttpGet] in a controller.

Route constraints and prioritisation

app.MapGet("/orders/{id:int}", (int id) => $"Order {id}");        // ONLY an integer
app.MapGet("/orders/{id:guid}", (Guid id) => $"Order {id}");       // ONLY a GUID
app.MapGet("/orders/search", () => "wyszukiwanie");                     // bardziej SPECYFICZNY - wygrywa

Endpoint Routing determines the priority of matching itself based on how specific the route is (the literal segment search beats the {id} parameter), with no need to set the registration order by hand, as was necessary in older routing systems.

A full example in Web API - how it fits together in practice

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddAuthentication(/* ... */);
builder.Services.AddAuthorization();
builder.Services.AddScoped<IOrderService, OrderService>();

var app = builder.Build();

app.UseRouting();               // (1) dopasowanie trasy

app.Use(async (context, next) =>
{
    var endpoint = context.GetEndpoint();
    var requiresAuth = endpoint?.Metadata.GetMetadata<IAuthorizeData>() != null;
    Console.WriteLine($"{context.Request.Path} -> wymaga auth: {requiresAuth}");
    await next();
});                              // (2) a custom middleware, ALREADY SEES the endpoint metadata

app.UseAuthentication();
app.UseAuthorization();         // (3) blocks the request if [Authorize] is not satisfied

app.UseEndpoints(endpoints =>   // (4) dopiero TU faktyczne wykonanie
{
    endpoints.MapControllers();

    endpoints.MapGet("/orders/{id:int}", async (int id, IOrderService service) =>
    {
        var order = await service.GetOrderAsync(id);
        return order != null ? Results.Ok(order) : Results.NotFound();
    });
});

app.Run();

This example shows the full point of the split: the custom logging middleware (2) and UseAuthorization() (3) both benefit from the endpoint having already been matched in step (1), before its code actually runs in step (4) - regardless of whether it is a controller (MapControllers()) or a Minimal API (MapGet).

Summary

Endpoint Routing separates route matching (UseRouting()) from its execution (UseEndpoints()/mappings), giving middleware in between access to the matched endpoint's metadata (through HttpContext.GetEndpoint()) - this is the mechanism that UseAuthorization() relies on (blocking based on [Authorize] before the code runs), and also the shared foundation for controllers, Minimal API, Blazor, gRPC and SignalR in ASP.NET Core.

Buy me a coffee