Create Custom Middleware In An ASP.NET Core Application

Introduction

 
One of the major features in ASP.NET Core is the new request pipeline which is available for the developer to customize according to the requirements of the application. In the request pipeline, several middleware components can be added to handle authentication, authorization, logging to files, etc. Although we have a long list of middleware’s available to us for use, there might be situations where we need to design and develop our own middleware component and add this to the request pipeline in order to execute it with every request. In today’s article, we will look at creating a simple middleware component.
 

Creating the Custom Middleware component

 
We will create the Middleware component using Visual Studio 2019 Community Edition. First, we will create a simple ASP.NET Core MVC application, as shown below:
 
Create A Custom Middleware In An ASP.NET Core Application
 
Create A Custom Middleware In An ASP.NET Core Application
 
Next, we will create a new folder called “Middlewares” in the main project, as shown below: 
 
Create A Custom Middleware In An ASP.NET Core Application
 
Next, we will add a new Middleware component by adding a new item: 
 
Create A Custom Middleware In An ASP.NET Core Application
 
Now, we will add the below code:
  1. using System.Diagnostics;  
  2. using System.IO;  
  3. using System.Threading.Tasks;  
  4. using Microsoft.AspNetCore.Builder;  
  5. using Microsoft.AspNetCore.Http;  
  6.   
  7. namespace WebAppMiddleware.Middlewares  
  8. {  
  9.     // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project  
  10.     public class CustomMiddleware  
  11.     {  
  12.         private readonly RequestDelegate _next;  
  13.   
  14.         public CustomMiddleware(RequestDelegate next)  
  15.         {  
  16.             _next = next;  
  17.         }  
  18.   
  19.         public async Task Invoke(HttpContext httpContext)  
  20.         {  
  21.             using var buffer = new MemoryStream();  
  22.             var request = httpContext.Request;  
  23.             var response = httpContext.Response;  
  24.   
  25.             var stream = response.Body;  
  26.             response.Body = buffer;  
  27.   
  28.             await _next(httpContext);  
  29.   
  30.             Debug.WriteLine($"Request content type:  {httpContext.Request.Headers["Accept"]} {System.Environment.NewLine} Request path: {request.Path} {System.Environment.NewLine} Response type: {response.ContentType} {System.Environment.NewLine} Response length: {response.ContentLength ?? buffer.Length}");  
  31.             buffer.Position = 0;  
  32.   
  33.             await buffer.CopyToAsync(stream);  
  34.   
  35.         }  
  36.     }  
  37.   
  38.     // Extension method used to add the middleware to the HTTP request pipeline.  
  39.     public static class CustomMiddlewareExtensions  
  40.     {  
  41.         public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)  
  42.         {  
  43.             return builder.UseMiddleware<CustomMiddleware>();  
  44.         }  
  45.     }  
  46. }  
As we can see in the above code, we simply write some details related to the request and response objects in the Invoke method which is the place to add our custom logic. Also, note that we use the _next request delegate to pass the control to the next middleware.
 

Using the Custom Middleware Component

 
Finally, we will plug this new Middleware component into the Request Pipeline (Configure method of the Startup class) by using the extension method defined in the CustomMiddlewareExtensions static class. 
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Microsoft.Extensions.Hosting;  
  6. using WebAppMiddleware.Middlewares;  
  7.   
  8. namespace WebAppMiddleware  
  9. {  
  10.     public class Startup  
  11.     {  
  12.         public Startup(IConfiguration configuration)  
  13.         {  
  14.             Configuration = configuration;  
  15.         }  
  16.   
  17.         public IConfiguration Configuration { get; }  
  18.   
  19.         // This method gets called by the runtime. Use this method to add services to the container.  
  20.         public void ConfigureServices(IServiceCollection services)  
  21.         {  
  22.             services.AddControllersWithViews();  
  23.         }  
  24.   
  25.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  26.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  27.         {  
  28.             app.UseCustomMiddleware();  
  29.   
  30.             if (env.IsDevelopment())  
  31.             {  
  32.                 app.UseDeveloperExceptionPage();  
  33.             }  
  34.             else  
  35.             {  
  36.                 app.UseExceptionHandler("/Home/Error");  
  37.                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
  38.                 app.UseHsts();  
  39.             }  
  40.             app.UseHttpsRedirection();  
  41.             app.UseStaticFiles();  
  42.   
  43.             app.UseRouting();  
  44.   
  45.             app.UseAuthorization();  
  46.   
  47.             app.UseEndpoints(endpoints =>  
  48.             {  
  49.                 endpoints.MapControllerRoute(  
  50.                     name: "default",  
  51.                     pattern: "{controller=Home}/{action=Index}/{id?}");  
  52.             });  
  53.   
  54.         }  
  55.     }  
Now, when we run the application, this new middleware component will be run with each request. Let's navigate to the privacy page and we will see the below output in the window:
 
Create A Custom Middleware In An ASP.NET Core Application
Create A Custom Middleware In An ASP.NET Core Application
 

Summary

 
In this article, we looked at how to create a simple middleware component and add it to the request pipeline in an ASP.NET Core MVC application. As we have seen, this process is quite simple and straight-forward and can be used to extract particularly useful information as well as carry out desired actions while the request and response are passing through the application pipeline. For this example, we simply wrote some information related to the request and response types and sizes. However, more complex scenarios can also be implemented in the same easy-to-develop manner.


Similar Articles