Create a custom middleware pipeline using .NET Core

Huzaifa Asif
Dec 18, 2018 · 2 min read
Photo by Fabian Grohs on Unsplash

What is middleware?

Middleware are small C# components that are assembled into an application pipeline to handle requests and responses.

Each component can choose whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component in the pipeline. Request delegates are used to build this request pipeline, which are then used to handle each incoming HTTP request to your application.

Configuring the HTTP pipeline

Middleware components are setup in the Configure method of the Startup class using one or more of the following extension methods on the IApplicationBuilder:

  • Use
  • Run
  • Map
public void Configure(IApplicationBuilder app)

Ordering of these middleware components is important as it will be the order in which they are invoked on incoming requests and for outgoing responses it will be called in the reverse order.

Create custom middleware

Time to create our own middleware and plug it into the application pipeline.

Create the CustomLoggerMiddlewareclass that would first log a message when the application is handling incoming request and log another message when returning a response back.

public class CustomLoggerMiddleware
private readonly RequestDelegate _next;
private readonly ILogger _logger;

We also need to create an extension method to expose our middleware through IApplicationBuilder.

public static class CustomLoggerExtension
public static IApplicationBuilder UseCustomLogger(this IApplicationBuilder builder)
return builder.UseMiddleware<CustomLoggerMiddleware>();

Call the extension method in the Configuremethod in the Startup.cs class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
You should see a similar output from the ASP.NET Core Web Server after starting the web application

As you can see, the idea behind the middleware pipeline is quite simple, but it’s very powerful and it’s equally as simple to create your own middleware classes.

That’s all for this article and if you enjoyed it please don’t forget to send me a clap or two!!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store