In an ASP.Net Core project, I'm writing a logging middleware to log all Http responses. I was following this SO question:
public async Task InvokeAsync(HttpContext httpContext)
{
Stream originalResponseStream = httpContext.Response.Body;
try
{
// log the response
using (MemoryStream responseStream = new MemoryStream())
{
httpContext.Response.Body = responseStream;
await this.nextMiddleware.Invoke(httpContext);
httpContext.Response.ContentLength = responseStream.Length;
responseStream.Seek(0, SeekOrigin.Begin);
await responseStream.CopyToAsync(originalResponseStream, 1024 * 16);
Logger.LogHttpResponse(httpContext, session);
}
}
finally
{
httpContext.Response.Body = originalResponseStream;
}
}
and then I have the Logger as a seperate project and Logger.LogHttpResponse
has the following code:
void LogHttpResponse(HttpContext context)
{
var body = new StreamReader(context.Response.Body, UTF8Encoding.UTF8).ReadToEnd();
// log body
}
The issue I'm facing right now, when creating a StreamReader, I get "Cannot access a closed Stream." exception. To get around the exception, i need to remove the using statement of MemoryStream in the middleware.
I'm not sure why the Response.Body stream was closed before leaving the using statement?
How to fix the exception properly?