I'm building a piece of middleware that automatically logs the information of inbound requests and their responses from an API. As part of that I would like to be able to log the body of the request, however this is a bit more difficult since I'm working with streams.
Currently, the middleware will read the body and log it, however since I'm reading the body using a StreamReader the contents of the body becomes essentially null after, since it's been read. Because of this the request continues and I'm getting "A non-empty request body is required."
errors since there's no body present any longer in the request.
I want to be able to copy the stream over to a new variable so that I can read the second variable and log the body while keeping the original body of the request intact so it can proceed and be processed by my controller.
I've tried the below, but since this just creates a reference to the stream, the original is still affected.
public void AddInboundDetails(HttpRequest request)
{
var bodyStreamCopy = request.Body;
Add("requestBody", ReadStreamAsString(bodyStreamCopy));
}
private string ReadStreamAsString(Stream input)
{
StreamReader reader = new StreamReader(input, Encoding.UTF8);
return reader.ReadToEnd();
}
I've read about Stream.CopyTo in the docs, but since this is again reading the original stream it feels like this will just produce the same problem.
Update, same issue:
request.EnableBuffering();
var body = request.Body;
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
await request.Body.ReadAsync(buffer, 0, buffer.Length);
var bodyAsText = Encoding.UTF8.GetString(buffer);
request.Body = body;