Middleware
Last updated
Last updated
To understand what Middleware is, we must first understand the concept of Request Pipeline. Request pipeline is a mechanism that handles an input request and ends with a response as an output. The pipeline shows how the application responds to the HTTP Request.
Requests coming from the browser will go through the Kestrel web server, then through the pipeline and back when processing is complete to return to the client.
The individual components that make up this pipeline are called middleware. Middleware is the component that plays a role in affecting the request pipeline and connecting together into a chain, the first middleware receives the HTTP Request, processes it and can pass it on to the next middleware or immediately return the HTTP Response. This sequence of middleware in such order is called a pipeline.
First, the incoming HTTP Request. The Kestrel web server picks up the request and creates an HttpContext and assigns it to the first Middleware in the request pipeline.
The first middleware will receive the request, process it and assign it to the next middleware. This process continues until the final middleware is reached. It's up to you how many middleware you want your pipeline to have.
The last middleware will return the request to the previous middleware, and will interrupt the process in the request pipeline.
Each middleware in the pipeline will sequentially get a second chance to recheck the request and modify the response before it is returned.
Finally, the response will go to Kestrel, it will return the response to the client. Any middleware in the request pipeline can interrupt the request pipeline in place with the simple step of not assigning the request any further.
Middleware is the bridge between user and system interaction. Act as an intermediary between the request/response and the processing logic inside the web server, for example:
User authentication is required to decide if they are allowed access to the current route.
Requires login
User redirects
Change/normalize the parameters
Handle input request and generated response,...