liveBook · Manning

Use

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

Use is an ASP.NET Core extension method that adds inline middleware to an application's request-processing pipeline.

Use is an ASP.NET Core extension method for adding general-purpose inline middleware to the request-processing pipeline. It can inspect or modify requests, generate responses, or pass requests to later middleware. section 31.1.3

The middleware lambda receives the current HttpContext and a Func<Task> representing the remaining pipeline. Calling next() continues processing; omitting it short-circuits the request. section 31.1.3

Respond to a health check

app.Use(async (HttpContext context, Func<Task> next) => { if (context.Request.Path.StartsWithSegments("/ping")) { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("pong"); } else { await next(); } }); Requests beginning with /ping receive pong immediately; other requests continue to the next middleware.

Use middleware can run code before and after the rest of the pipeline. Register response changes such as headers with Response.OnStarting, because later middleware may begin streaming the response after next() returns.

Inline Use calls are convenient for small components, but reusable middleware is usually better expressed as a class with a RequestDelegate constructor and public Invoke(HttpContext) method. This shape also supports dependency injection in Invoke. section 31.1.4 section 31.4

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

How deep it goes
Explains lambda parameters, continuation control, short-circuiting, response timing, and class-based alternatives.
Examples
Demonstrates a /ping health check, response security headers, and equivalent class-based middleware.
What it assumes
Assumes familiarity with ASP.NET Core request pipelines while introducing custom middleware from basic lambda expressions.
What you can do after
Build it from scratch as inline middleware that continues or short-circuits requests using next().
How it connects
Connects Use to middleware pipelines, HttpContext, RequestDelegate, Run, Map, dependency injection, and endpoint routing.

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.