Middleware in ASP.NET Core
Middleware is a series of components present in this processing pipeline.
An ASP.NET Core Middleware is a component that sits on the HTTP Request Pipeline and handles requests and responses. It controls how our application responds to HTTP requests.
Middleware components are modular, reusable components that form the building blocks of the request processing pipeline in an ASP.NET Core application. Middleware components are responsible for handling specific tasks during the processing of incoming HTTP requests and outgoing responses. They enable you to add various functionalities to your application, such as authentication, routing, logging, compression, and more
There can be one or more Middlewares sitting on the HTTP pipeline in a line.
When a new HTTP request arrives, it is send to the first middleware which inspects it. This Middleware will peform one of the two things:
1. Generates a response and send it back to the client (request initiator).
2. Pass the HTTP Request to the next Middleware in the pipeline.
Order of Processing
middleware components are executed in the order they are added to the pipeline, and each component has the ability to process requests, modify responses, or perform other actions before and after passing the request to the next middleware component. Middeware are processed on the same order in which they are applied for a request. MD1 > MD2 > MD3 > MD4.
The response is returned to the client in the “opposite” order in which the middleware are processed. MD4 > MD3 > MD2 > MD1
Why Middleware is used in ASP.NET Core?
Middeware can be used to build high class features like authentication, authorization, logging and so on. Middeware
1. Sits between the requestor and the target.
2. Can directly modify the response.
3. Can log things.
4. Can use the data within the request to generate the response.
Built-in Middleware in ASP.NET Core
There are large number of Built-in Middleware in ASP.NET Core, we can use only the ones which we need in our app. Middleware is a great place to do the following:
Error handling and logging