Does the error "Can't read a closed stream" come from your reading? Isn't it thrown afterwards?
I guess that it is thrown afterwards and it is because you read and close the stream, but the middleware tries to read it after the OnAfterRender is finished.
You can try to set to the r.Content the stream you actually want to return back to the response.