What is the difference between app.Use, app.Run and app.Map?

ASP.NET Core Middleware Basic 1–2 Yrs2–3 Yrs Conceptual 1 min read

Quick Answer

app.Use adds middleware that can call next() to continue the pipeline (or not). app.Run adds a terminal middleware that never calls next — the pipeline ends there. app.Map / app.MapWhen / app.UseWhen branch the pipeline based on the request path or a predicate.

app.Use is the general form — the delegate gets next and decides whether to continue the pipeline. app.Run is terminal: it has no next, it just handles the request and the pipeline stops there, so it always goes last. app.Map branches the pipeline off based on a path prefix, and UseWhen branches on any predicate but then rejoins the main pipeline. Most custom middleware is a Use with work before and after the await next().

  • app.Use(async (ctx, next) => { /* before */ await next(); /* after */ }).
  • app.Run(async ctx => { await ctx.Response.WriteAsync("done"); }) — no next parameter.
  • app.Map("/admin", admin => { ... }) — requests starting with /admin go down a separate branch.
  • app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), api => { ... }) — like Map but rejoins the main pipeline after.