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
