When learning backend development, the concept of middleware is essential. In this article, I will explain everything you need to know about middleware.
What is Middleware?
Middleware is a component that we write in the application pipeline to handle requests and responses.
Flow of Execution
When a client sends a request to perform an action, the request first goes to the Kestrel server. Kestrel listens on a specified port and is responsible for handling low-level network communication. Kestrel parses the incoming request and converts it into a form that the ASP.NET Core application can understand, encapsulated in an HttpContext
object.
after that the control pass through the application pipeline where we defined our middleware . Middleware modify and perform some actions on the httpcontext requests and responses and then pass it to the next middleware with the next deligate .
Note:
Each middleware can terminate the chain before reaching the endpoints and not pass the request to the next middleware, which is called short-circuiting the request.
Back to the Flow:
Now, one by one, each middleware is executed until it reaches the terminal middleware and calls the action method. When the action is performed, it returns a response. The response is then passed back through the application pipeline, where even the middleware may perform some actions on the response. Finally, the response is sent to the Kestrel server, which sends it back to the client.
Some Important Points About Middleware:
- Middlewares are chained one after the other so its mean they are executed in exactly the same way the are defined
- In order to call the next middleware in request pipeline we need to expiclity call it by calling next method although they are no rules that each middleware should call to the next middleware that middleware called terminate middleware or short circuit
- Each middleware should perform a single task
Types of Middleware :
Different people categorized middleware in different types according to used cases but in my opinion there are two major types of middleware
Built-in Middleware :
Asp.net core provide different types of built in middleware that perform different actions
app.useRouting :
Handle Routes incoming requests to the appropriate endpoint
app.useAuthentication:
Handles user authentication, validating credentials like tokens or cookies
app.useAuthrization:
Checks if the authenticated user has the required permissions to access a resource
app.useStaticFiles:
Serves static files such as images, CSS, and JavaScript directly from the file system.
Custom Middleware :
We can also make our custom middlewares
I create an empty project in which i make custom middleware
But the output is this, so it means only one middleware executed. Although we read that the middleware executes one after the other.
Why is the second middleware not executed?
Due to the reason of short-circuiting middleware or terminal middleware, because the previous one did not call the next middleware.
Middleware Chaining:
This is not possible with the help of app.Run
because it takes a callback function that accepts only one parameter, and app.Use
takes two parameters: the first one is HttpContext
and the second one is the request delegate. Anywhere in the chain, we simply cannot call the next
method; it is not necessary to call the next middleware.
The upper I do the middleware chaining and the output is
now find out why the middleware 4 not executed and comment your answer .
Custom middleware :
We create our class for middleware when we need to write a large amount of code. To use this in the Program.cs
file, we need to add it to the services and then call it using app.UseMiddleware.
Now here is our complete example
and the output of this example is
Why does the custom middleware finish executing last?
The reason is that I added this in the context after calling the next
method, which means it is added to the context when control goes back, terminating the middleware.
Conclusion
Middleware is a powerful tool in .NET Core that allows you to modify incoming requests and outgoing responses. It can be used to perform a wide range of tasks such as authentication, logging, compression, and caching.
When using middleware in your .NET Core applications, it is important to use it sparingly, order the middleware components carefully, use terminal middleware components when appropriate, and test your middleware thoroughly. By following these best practices, you can ensure that your middleware components are effective and efficient.
If you find it helpful, follow me and appreciate the story. See you soon.