Middleware app.Use vs. app.Run in Asp.net Core

Middleware app.Use vs. app.Run in Asp.net Core
These two methods are fundamental for adding middleware to your pipeline, but they have key differences:
app.Use(async (context, next) => { … })
Non-Terminal Middleware: This type of middleware typically performs some action and then calls the next delegate to pass control to the next middleware in the pipeline.
Can Modify Request/Response: It can change the request or response before passing it along.
Examples: Authentication, logging, custom headers, etc.
app.Run(async (context) => { … })
Terminal Middleware: This middleware doesn’t call next; it ends the pipeline and generates the response itself.
Often Used for the Final Response: It’s commonly used for handling requests that don’t need further processing (e.g., returning a simple message).
Can’t Modify Request: Since it’s the end of the line, it cannot modify the request before passing it on.
 
 
Code 1: The Consequence of Multiple app.Run Calls
app.Run(async (HttpContext context) => {
    await context.Response.WriteAsync(“Hello”);
});
 
app.Run(async (HttpContext context) => {
    await context.Response.WriteAsync(“Hello again”);
});
 
app.Run();
 
In this code, only the first app.Run middleware will be executed. It terminates the pipeline by writing “Hello” to the response, and the subsequent app.Run (which would write “Hello again”) never gets a chance to run.
 
 
Code 2: Chaining Middleware with app.Use and app.Run
//middlware 1
app.Use(async (context, next) => {
    await context.Response.WriteAsync(“Hello “);
    await next(context);
});
 
//middleware 2
app.Use(async (context, next) => {
    await context.Response.WriteAsync(“Hello again “);
    await next(context);
});
 
//middleware 3
app.Run(async (HttpContext context) => {
    await context.Response.WriteAsync(“Hello again”);
});
 
This code demonstrates a correct way to chain middleware.
The first app.Use writes “Hello ” to the response and then calls next to pass control to the next middleware.
The second app.Use writes “Hello again ” and also calls next.
The final app.Run (which is terminal) writes “Hello again” and ends the pipeline. The result would be output of “Hello Hello again Hello again”.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply