I'm writing some middleware for an ASP.NET Core 7 minimal API project.
At this stage, I would just like to be able to read the request body being sent in, and then the response body that is being sent out, and dump them to the console.
Reading the request seems easy enough. My middleware contains the following...
public async Task InvokeAsync(HttpContext httpContext) {
try {
httpContext.Request.EnableBuffering();
string requestBody = await new StreamReader(httpContext.Request.Body, Encoding.UTF8).ReadToEndAsync();
httpContext.Request.Body.Position = 0;
Console.WriteLine($"Request body: {requestBody}");
} catch (Exception ex) {
Console.WriteLine($"Exception reading request: {ex.Message}");
}
await _next(httpContext);
}
This works fine. However, when I try to read the response body, I get an exception. I tried inserting the following (similar to what's found on many SO answers and blog posts)...
try {
using StreamReader reader = new(httpContext.Response.Body);
httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
string responseBody = await reader.ReadToEndAsync();
httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
Console.WriteLine($"Response body: {responseBody}");
} catch (Exception ex) {
Console.WriteLine($"Exception reading response: {ex.Message}");
}
However, this gives an exception System.ArgumentException: Stream was not readable.
One thing that confuses me is that according to the Microsoft docs, middleware is called twice, once when the request comes in (before the specific endpoint code has been called), and a second time when the response is being sent out (after the endpoint code has done its stuff). I can see that my middleware is only being called when the request comes in, so even if the code above worked, I don't see how it would get the response, as that hasn't been generated by the endpoint code yet.
I've searched around, but haven't found anywhere that clarifies this point.
Anyone able to advise what I'm doing wrong? Thanks