Purpose
- In app. Run Only terminal middleware delegate is currently being added to the pipeline.
- app.Use function adds a middleware delegate that is not terminal to the pipeline.
Execution:
- app. Run Ends the pipeline after processing the request that was made.
- In app.Use, the request is processed, and then it is sent on to the subsequent middleware element in the pipeline.
The end result
- In app. Run The response is delivered to the client in a direct manner.
- In app.Use, Context of the request is modified, and then it is passed on to the subsequent middleware.
Felexible
- app. Run , only deals with the request directly, thus its flexibility is limited.
- app.Use allows for various middleware components to be chained together, making it more flexible.
Testing
- app. Run is very difficult to test, because of the terminal nature of the substance.
- The fact that app.Use is a bigger pipeline makes it simpler to test in isolation.
Use cases
- app. Run is suitable for projects that are straightforward and do not require any additional processing.
- app.Use is suitable for extremely complicated applications that call for a number of different processing steps.
Syntax
- app.Run(async context => await context.Response.WriteAsync("…"));
- app.Use.Authentication(); app.Use.Authorization();
Middleware Execution Flow - How MIddleware in Pipeline works in following Use Case
Use case - execution sequence when you have four middlewares added in the order: Use, then Run, then another Use, and finally another Run.
In ASP.NET Core, the middleware pipeline processes requests and responses in a specific order. Here's how the execution unfolds with your specified middleware sequence:
- First Use Middleware: This middleware is invoked first. It can perform operations on the incoming request and then call next(), passing control to the next middleware.
- First Run Middleware: This is a terminal middleware. Once invoked, it handles the request and generates a response, terminating the pipeline. No subsequent middleware is executed for this request.
- Second Use Middleware: This middleware is never reached for the current request because the first Run middleware has already terminated the pipeline.
- Second Run Middleware: Similar to the second Use middleware, this is also never reached for the current request due to the termination by the first Run middleware.