EP 20 : What is middleware and multiple ways to create middleware in .NET Core ?
Read Time : 3 Mins
In today’s newsletter we are going to discuss
What is middleware ?
How middleware works ?
Multiple ways of creating middlewares
What is middleware ?
Middleware is a software assembled into an app pipeline to handle request and response.
In simple words middleware gives us the facility to add additional logic before and after the HTTP request.
How middleware works ?
Suppose we have three middlewares in our app then for each middleware we enter two time.
First middleware logic is performed then we send it to next middleware
Secondly when request comes back after executing the next middlewares
Multiple ways of creating middlewares
We have three ways to create middleware in .NET Core
Request delegate (Most simple)
By convention
Using middleware factory
Creating middleware using Request Delegate
In this way we can create middleware using app.Use
in our Program.cs
We can add our logic that we want to perform before or after this middleware.
If you don’t want to call next middleware we can achieve that by not invoking next.
Our Program.cs file would look like this :
To learn more about this technique visit Microsoft Docs
Creating middleware by Convention
It has three steps :
Create a class of your middleware and pass
RequestDelegate
in its constructor.Now add a method responsible for logic before and after the middleware, pass it
HttpContext
Add middleware in Program.cs
After first two step our code would be like :
Tell the Program.cs about this middleware by using app.UseMiddleware<name>()
Creating middleware using Factory
This is modified version of conventional way , in this we create our class and inherit it from IMiddleware
. In this way IMiddleware enforces us to implement InvokeAsync
method. So the code looks like :
One last step is to informing Program.cs
about this middleware , but this time we can not do it only with app.UseMiddleware
, we have to add it in built-in DI container. We have to register its service as well like this :
The factory method is most appreciated by developers because it has less chance of error and it is more clean.
Explore more about last two approaches from Microsoft Docs
Whenever you’re ready , there are 3 ways I can help you
Promote yourself to 4300+ subscribers by sponsoring my Newsletter (Reach me at mwaseemzakir@gmail.com)
Become a Patron and get access to 130+ .NET Questions and Answers , I add 2-5 new questions every week
Get my FREE eBook from Gumroad that contains 30 .NET Tips (Downloaded by 2400+ and 100+ five star ratings)
Special Offers 📢
Ultimate ASP.NET Core Web API Second Edition - Premium Package
10% off with discount code: 9s6nuez
Thanks for this