We are trying to create a middleware that allows you to log in to an external service the body of an HTTP response.
We tried replacing it with a MemoryStream, but when we try to read it it turns out to be closed.
Could anyone help us?
Thanks in advance
Here is the code:
public class LogMiddleware
{
private readonly RequestDelegate _next;
public LogMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var originBody = context.Response.Body;
try
{
var memStream = new MemoryStream();
context.Response.Body = memStream;
await _next(context).ConfigureAwait(false);
memStream.Position = 0;
var responseBody = new StreamReader(memStream).ReadToEnd();
var memoryStreamModified = new MemoryStream();
var sw = new StreamWriter(memoryStreamModified);
sw.Write(responseBody);
sw.Flush();
memoryStreamModified.Position = 0;
await memoryStreamModified.CopyToAsync(originBody).ConfigureAwait(false);
}
finally
{
context.Response.Body = originBody;
}
}
}