liveBook · Manning

Endpoint middleware

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

Endpoint middleware is the ASP.NET Core middleware component that executes the endpoint selected for an incoming request.

Endpoint middleware executes the endpoint selected for an incoming request and produces its response. In ASP.NET Core, EndpointMiddleware typically sits at the end of the middleware pipeline; routing middleware selects the endpoint earlier in the pipeline. section 6.2 section 3.7.2

WebApplication normally adds both routing and endpoint middleware automatically. Middleware between them can see the selected endpoint and react before it executes. If no route matches, endpoint middleware does not generate a response. section 6.5 section 6.2

app.MapGet("/", () => "Hello World!");
app.MapGet("/person", () => new Person("Andrew", "Lock"));

These MapGet calls define endpoints; they do not add middleware. For GET /, routing selects the first endpoint and endpoint middleware executes it to return Hello World! A request to /person selects the second endpoint and returns a JSON representation of the Person. section 3.7.2 section 4.2.3

Order matters. Earlier middleware can handle a request and return a response without passing it on, so the endpoint may never execute. For example, a welcome page registered for / before endpoint middleware can return its own HTML instead of the minimal API response. section 4.2.3 section 4.1

For minimal API handlers, the return type determines how the response is generated:

  • A string becomes a text/plain response; an object such as Person becomes JSON. section 5.3
  • An IResult executes its ExecuteAsync method and can customize the response, including its status code. section 5.3
  • A void or Task return produces a 200 response with no body. section 5.3

The same routing infrastructure supports Razor Pages and MVC. For a Razor Page, routing first selects the page; execution then selects a page handler using the HTTP verb and an optional handler route value. section 6.2 section 15.2

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

How deep it goes
Explains pipeline placement, endpoint selection, short-circuiting, return-type handling, and Razor Page handler selection.
Examples
Uses Hello World and Person endpoints, a welcome-page short circuit, and a Razor Page with multiple handlers.
What you can do after
Apply it through ASP.NET Core WebApplication by mapping endpoints and arranging middleware in the pipeline.
How it connects
Connects endpoint routing, middleware pipelines, route templates, minimal APIs, Razor Pages, and MVC.

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.