What is wrong with this code? Moreover how do I fix it?
public class BodyStreamMiddleware
{
private readonly RequestDelegate _next;
public BodyStreamMiddleware(RequestDelegate next) { _next = next; }
public async Task Invoke(HttpContext context)
{
// Replace the FrameRequestStream with a MemoryStream.
// This is because the MemoryStream is rewindable, the FrameRequestStream is not.
// This allows ExceptionFilters to read the body for logging purposes
string bodyAsText;
using (var bodyReader = new StreamReader(context.Request.Body))
{
bodyAsText = bodyReader.ReadToEnd();
}
var bytesToWrite = Encoding.UTF8.GetBytes(bodyAsText);
using (var memoryStream = new MemoryStream())
{
memoryStream.Write(bytesToWrite, 0, bytesToWrite.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
context.Request.Body = memoryStream;
// Tell ASP.NET core to dispose the memory stream when the request ends
// (only added in desperation)
context.Response.RegisterForDispose(memoryStream);
await _next.Invoke(context);
}
}
}
When I run a Veracode scan over the above it gives me
404 Improper Resource Shutdown or Release
I understand that a downstream process could grab a reference to the memory stream and hang onto it, but fail to see how that is any different to the default asp.net behaviour (i.e. something could grab hold of the FrameRequestStream).