CodexBloom - Programming Q&A Platform

Unexpected Behavior of Custom Middleware in ASP.NET Core 6 with Request Body Manipulation

👀 Views: 68 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
asp.net-core middleware request-body C#

I need some guidance on I'm currently developing an ASP.NET Core 6 application and I've implemented a custom middleware to manipulate the request body before it reaches the controller... However, I'm running into an issue where the request body appears to be empty when accessed later in the pipeline, leading to a `BadRequest` response from the API. Here's the middleware implementation: ```csharp public class RequestBodyMiddleware { private readonly RequestDelegate _next; public RequestBodyMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { context.Request.EnableBuffering(); using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, leaveOpen: true)) { var bodyAsText = await reader.ReadToEndAsync(); context.Request.Body.Position = 0; // Reset the stream position // Manipulate the body as needed context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsText.ToUpper())); // Example manipulation } await _next(context); } } ``` In `Startup.cs`, I register the middleware like this: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<RequestBodyMiddleware>(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` When I make a POST request to my API with a JSON body, the middleware executes without error, but in my controller, when I try to read the request body again, it throws an `InvalidOperationException` stating that the stream has already been read or is empty. I've tried adding `context.Request.EnableBuffering()` but it seems like the request body is still not accessible in the controller. I've also checked that the content type is set correctly and that the request body is not empty when it enters the middleware. Is there something I'm missing here? How can I ensure the request body is readable in the controller after manipulating it in the middleware? This is my first time working with C# LTS. Any pointers in the right direction? This is happening in both development and production on Ubuntu 20.04. Is this even possible?