- Whats is Middleware?
Middlewares are some components, we place them into software pipeline to handle request and responses. Middlewares are some methods actually.
- We can use Middlewares in several ways, such as:
- In
program.cs, Using app.run() and app.use(). In this case, I should mention, app.run is short cercuiting middleware. If we wanna make chaining middleware, we have to use app.use().
- By making custom middlewares. We can make two kinds of custom middlewares, such as:
- By implementing
IMiddleware interface. And another one is by conventional middleware.
- In both process, we should implement
extansion method to give a better look. We use UseMiddleware<>() to call the main Middleware.
- In Imiddleware approach whe have to add the middleware in the builder services as a trancient scoped service.
- Conventional aproach doesnt nefo
IMiddleware approach has a transient scope, so, it can take scoped objects like Dbcontext. Conventional approach cannot take it as it’s object was make while starting the software once in the beginning through reflection and dont make objects per each request.
- We must put middlewares right serial.
- We can use
UseWhen to add conditional branching in middlewares.