How to read the request body in ASP.NET Core Middleware?

In this article, we will write code to Read the request body in ASP.NET Core Middleware. To demonstrate this we will create a custom middleware.

What is Middleware?

Middleware in .NET Core is similar to HttpHandlers and HttpModules which were part of classic ASP.NET. When a user hits the request from a client such as a browser then before it hits the controller, it has to pass through multiple HTTP processes and here Middleware comes into the picture. Read Full Article

Create a Custom Middleware to read the request body

There is some built-in middleware available in .NET Core and they have their own specific task. To read the request body in ASP.NET Core Web API, we will create a custom middleware.

Visual Studio gives you a readymade template to create custom middleware.

Right-click on your project in Solution Explorer and click “Add New Item”. In the search box type “Middleware” and you will see Middleware Class in the result.

Add a middleware and name it CustomMiddleware.cs

Declare a read-only property –

private readonly RequestDelegate _next;

Create a constructor –

public CustomMiddleware(RequestDelegate next)
{
   _next = next;
}

Add Invoke() method in the class

public async Task Invoke(HttpContext context)
{
  context.Request.EnableBuffering();
  var bodyAsText = await new System.IO.StreamReader(context.Request.Body).ReadToEndAsync();
  context.Request.Body.Position = 0;
  await _next.Invoke(context);
}

The complete code snippet of the CustomMiddleware.cs file is –

    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;
        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext context)
        {
            context.Request.EnableBuffering();
            var bodyAsText = await new System.IO.StreamReader(context.Request.Body).ReadToEndAsync();
            context.Request.Body.Position = 0;
            await _next.Invoke(context);
        }
    }
    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomMiddleware>();
        }
    }

Now, in Configure() method of the startup.cs file, add the below code –

app.Use((context, next) =>
            {
                context.Request.EnableBuffering();
                return next();
            });
            app.UseCustomMiddleware();

Run your application and put a debugger at Invoke() method in the CustomMiddleware class and you will get the Request Body Content.

Why read the request body using Custom Middleware?

Now, you have got the request body using custom middleware. The question is why read the request body using Custom Middleware?

There could be numerous uses of reading request bodies in Middleware

  • In case you want to log the footprint then you can use this.
  • If you want to manipulate or modify the request body for some purpose, in that case, it is useful

Conclusion

In this article, we explored the way to read the request body in the ASP.NET Core Web API application. We can create a custom middleware to read this request body.

You may read articles on AZ 900.

1 thought on “How to read the request body in ASP.NET Core Middleware?”

  1. I enjoy what you guys are usually up too. This sort of clever work and exposure!
    Keep up the superb works guys I’ve added you guys to
    my personal blogroll.

    Reply

Leave a Comment

RSS
YouTube
YouTube
Instagram