wasAsked.

Have you used app.Use() and app.Run()? What's the difference?

Impetus · Role not specified · technical

Published

Year not specified · .NET

Community answers

Posted by wasAsked editorial collection

Yes — both add middleware to the ASP.NET Core request pipeline, but they behave differently. app.Use - Adds middleware that receives the context and a delegate for the next middleware. - It can run code before and after the rest of the pipeline, or short-circuit by not calling next. app.Use(async (context, next) => { context.Response.Headers["X-Request-Id"] = context.TraceIdentifier; await next(context); // continue the pipeline // code here runs after later middleware has finished }); app.Run - Adds terminal middleware. It receives only the context and never calls a next component, so the pipeline ends there. - Anything registered after app.Run is never reached for those requests. app.Run(async context => { await context.Response.WriteAsync("Hello from the end of the pipeline"); }); Related methods worth mentioning: - app.Map("/health", branch => ...) creates a branch for a path prefix. - app.MapWhen(predicate, branch => ...) branches on any condition. - app.UseWhen(predicate, ...) runs extra middleware conditionally and then rejoins the main pipeline. - app.UseMiddleware<T>() registers a class-based middleware, which is cleaner and testable for real logic. Where I have used them: - app.Use for small cross-cutting concerns such as adding correlation IDs, security headers or timing logs. - app.Run in minimal examples or as a final fallback response; in modern apps, endpoints (MapGet, MapControllers) usually terminate the pipeline instead. Gotchas: do not write to the response and then call next if later middleware also writes; do not change headers after the response has started; and remember that order of registration is the order of execution.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics