Creating custom middleware for ASP.NET Core
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"); await _next.Invoke(httpContext); } }
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) { return builder.UseMiddleware<GreetingMiddleware>(); } }
Now we can use it easily as app.UseGreeting()
. Enjoy!
Comments
- Anonymous
March 12, 2017
Hi,Nice article and great subject to write about, as for it s discussing about one of the fundamentals for developing application with .net core.Besides, there is a little misspelling on the class constructor.