ASP.NET Core provides a great flexibility to interrupt the HTTP request handling pipeline and customize it. The customization is done by something called as “Middleware”. There are tons of ready-made middleware available as Nuget packages. Even the MVC middleware is available as a Nuget package and is by default part of all ASP.NET Core project templates. But sometimes these Nugets do not solve our purpose and we need to create our own middleware. In this post we can see how we can achieve the same.
Middleware work by interrupting the HTTP pipeline and processing the
HttpContext object. After it is done processing, the middleware should hand over the context to the next middleware in pipeline. This is achieved by
RequestDelegate object which lives in the
Microsoft.AspNetCore.Http namespace. The middleware should also have a Invoke method which takes in a
HttpContext and then hands it to next method in pipeline. A complete class is shown below. It interrupts all Http request and writes “Hello from Middleware” to it.
public class GreetingMiddleware
private readonly RequestDelegate _next;
public VamMiddleware(RequestDelegate next)
_next = next;
public async Task Invoke(HttpContext httpContext)
await httpContext.Response.WriteAsync("Hello from Middleware");
To use this middleware, in your
Configure method of your
Startup.cs class, write
app.UseMiddleware<GreetingMiddleware>() . To make our middleware even more friendly to use, we can write an Extension method to it.
public static class GreetingExtensions
public static IApplicationBuilder UseGreeting(this IApplicationBuilder builder)
Now we can use it easily as
app.UseGreeting() . Enjoy!