| Muhammad Waseem

About Newsletter
Books
30 .NET Tips
Sponsorship
Multiple ways to create middleware
Jul 8, 2023
3 min read

Multiple ways to create middleware

Sponsor this Newsletter

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 ?

Multiple ways to create middleware in .NET Core*1

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 :

  1. Request delegate (Most simple)
  2. By convention
  3. 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 :

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next)
{
Console.WriteLine("BEFORE")
await next. Invoke();
Console.WriteLine("A FTER")
});
app.Run();

To learn more about this technique visit Microsoft Docs

Creating middleware by Convention

It has three steps :

  1. Create a class of your middleware and pass RequestDelegate in its constructor.

  2. Now add a method responsible for logic before and after the middleware, pass it HttpContext

  3. Add middleware in Program.cs

After first two step our code would be like :

public class ConventionMiddleware
{
private readonly RequestDelegate_next;
public ConventionMiddleware (RequestDelegate next) => _next = next;
public async Task IanvokeAsync(HttpContext context)
{
Console.WriteLine("BEFORE");
await_next(context);
Console.WriteLine("AFTER");
}
}

Tell the Program.cs about this middleware by using app.UseMiddleware<name>()

app. UseMiddleware<ConventionMiddleware>();

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 :

public class FactoryMiddleware: IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
Console.WriteLine("BEFORE");
await next(context);
Console.WriteLine("AFTER");
}

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 :

builder.Services.AddTransient FactoryMiddleware>();
app.UseMiddleware<FactoryMiddleware>();

The factory method is most appreciated by developers because it has less chance of error and it is more clean.

Diclamier : Image with *1 was copied from this URL

This article was originally published at https://mwaseemzakir.substack.com/ on Jul 8, 2023 .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place
Previous Next

Subscribe to Newsletter

Join 9,000 Software Engineers

Buy Me a Coffee

Enjoy my articles? Support me by buying a coffee!

Buy Me a Coffee

Muhammad Waseem

Resources
  • Books
  • Courses
Newsletter
  • Articles
  • Sponsorship
Books
  • 30 .NET Tips
  • 100 .NET Tips (Soon)
Author
  • About Us
  • Contact Us
Policy
  • Privacy Policy
  • Terms and Conditions
Interview
  • C# & .NET
  • Web API

Join my .NET newsletter and stay updated!

© 2025 Muhammad Waseem. All rights reserved.