Create a custom middleware pipeline using .NET Core

Huzaifa Asif
2 min readDec 18, 2018

--

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)
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
}

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;
public CustomLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<CustomLoggerMiddleware>();
}
public async Task Invoke(HttpContext context)
{
_logger.LogInformation("**Handling request: " + context.Request.Path + "**");
await _next.Invoke(context);
_logger.LogInformation("**Finished handling request.**");
}
}

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)
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseCustomLogger();
}
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!!

--

--