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:


Next, we will create a new folder called “Middlewares” in the main project, as shown below.

Next, we will add a new Middleware component by adding a new item.

Now, we will add the below code.
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace WebAppMiddleware.Middlewares
{
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
using var buffer = new MemoryStream();
var request = httpContext.Request;
var response = httpContext.Response;
var stream = response.Body;
response.Body = buffer;
await _next(httpContext);
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}");
buffer.Position = 0;
await buffer.CopyToAsync(stream);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class CustomMiddlewareExtensions
{
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomMiddleware>();
}
}
}



ovis ariesPosted Jun 24, 2022, 4:00 PM
How do you call your custom middleware on each http request?
Tan LUPosted Sep 24, 2020, 10:56 AM
In your code, I saw these lines: var stream = response.Body; response.Body = buffer; ... buffer.CopyToAsync(stream); in your code, I saw these lines: var stream = response.Body; response.Body = buffer; ...buffer.CopyToAsync(stream); where is the data comes from? why just write: var stream=buffer?