Create custom middleware in ASP.NET Core

You might be heard many times about ASP.NET Core Middleware and used it all the times knowing or unknowingly. One of the major feature inclusions in ASP.NET Core is new HTTP Request Pipeline, which is also available for developers to create and inject their own to HTTP Request Pipeline. The request pipeline is nothing but collection of middleware components to handle specific requirements such as Authentication, Authorization, logging, etc.

Before you continue reading this article if you would like to know what is middleware in ASP.NET Core? what is its role in HTTP Request Pipeline? What are the inline middleware functions available? Then you much first go through the article on ASP.NET Core Use(), Next(), Map() and Run() Middleware Extension Methods

ASP.NET Core Middleware

In this article we are going to cover,
  • Create custom middleware
  • Configure custom middleware to HTTP Pipeline

ASP.NET Core comes with many built in middleware modules. But there are cases you might be needed to create your own middleware to fulfill your requirement. In such scenarios you must go and build your requirement specific middleware.

In ASP.NET Core there are couple of ways to create custom middleware.
  1. Using IMiddleware interface
  2. Using extension method
Create custom middleware - IMiddleware interface approach

In this approach you need to create a class which implements from IMiddleware interface. And, then implement the InvokeAsync interface method as shown in below code:

[pre class="brush:csharp; toolbar: false;" title=""] public class MiddlewareUsingInterface : IMiddleware { public async Task InvokeAsync(HttpContext context, RequestDelegate next) { await context.Response.WriteAsync("This message is from Custom middleware message. The middleware is built using IMiddleware interface\n"); await next(context); } } [/pre]
Configure custom middleware - IMiddleware interface approach

Now we will add the above created custom middleware called MiddlewareUsingInterface to HTTP Request Pipeline.
First register the MiddlewareUsingInterface service as below in your Program.cs file: 

[pre class="brush:csharp; toolbar: false;" title=""] //Register middleware service builder.Services.AddTransient<MiddlewareUsingInterface>(); [/pre]
Now add the MiddlewareUsingInterface middleware in HTTP Pipeline, let’s inject the middleware as below:

[pre class="brush:csharp; toolbar: false;" title=""] //add middleware to request pipeline app.UseMiddleware<MiddlewareUsingInterface>(); [/pre]
When you the run above code, you get the output message from custom middleware as below.

ASP.NET Core Middleware using IMiddleware interface

Create custom middleware – Extension Method approach

In this approach you need to create a class with InvokeAsync method as shown below:

[pre class="brush:csharp; toolbar: false;" title=""] public class MiddlewareUsingExtensionMethod { private readonly RequestDelegate _next; public MiddlewareUsingExtensionMethod(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { await context.Response.WriteAsync("This message is from Custom middleware message. The middleware is built using Extension Method\n"); await _next(context); //Thie next() method calls the next middleware } } [/pre]
From the above code you can see that, RequestDelegate (a function) is passed to constructor, which is the next middleware to be called in side the InvokeAsync method.

And, now create an extension method to IApplicationBuilder class, which adds the above class as middleware to HTTP Pipeline as shown below:

[pre class="brush:csharp; toolbar: false;" title=""] public static class MyMiddlewareExtensions { public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<MiddlewareUsingExtensionMethod>(); } } [/pre]
 
Configure custom middleware – Extension Method approach

Here just call the middleware which is created as extension method on IApplicationBuilder object as shown below:

[pre class="brush:csharp; toolbar: false;" title=""] //add middleware to request pipeline app.UseMyCustomMiddleware(); [/pre]
Now let's run the app and see what the middleware outputs:

ASP.NET Core Middleware using extension method

That’s all brief about creating and configuring custom middleware in ASP.NET Core. Hope you have enjoyed with this article, and if you have any queries, please use the below comment box.

No comments:

Powered by Blogger.