Yes, the default flow provided is only available because the data is buffered only for a short time and cleared from the client. Therefore, you cannot rewind or read it.
The second attempt does not work because the original thread is never processed. You completely replaced the response body stream with a MemoryStream and threw away the original request, so nothing is written on it, and the client waits forever.
You should not forget that the stream for the client is in the original stream, you cannot just replace it with something else.
After calling await next() you should read the data from the MemoryStream and then write it to the original stream.
app.Use(async (context, next) => { var originalStream = context.Response.Body; var memoryStream = new MemoryStream(); context.Response.Body = memoryStream; await next();
Note
But keep in mind that this solution will buffer the whole response to server memory, so if you send large files, it will significantly degrade the performance of your ASP.NET Core application, especially if you submit files of several megabytes in size and often cause garbage collection.
And this will not only affect your static files, but also all your regular requests, because the MVC middleware is called after the static file middleware.
If you really want to change one (or a list of files) for each request, I would prefer that you do this inside the controller and send certain files there. Remember that if a given file is not found by the static file middleware, it will call the next one in the chain until it reaches the mvc middleware.
Just configure the route there, which will correspond to a specific file or folder and direct it to the controller. Read the file in the controller and write it to the response stream or just return the new pair (using return File(stream, contentType);