Hi,
I'm trying to log the response via the middleware of an aspnetcore Web API.
The only code I've been able to find to do this is the following
publicclassLogResponseMiddleware{privatereadonly RequestDelegate _next;privatereadonly ILogger _logger;publicLogResponseMiddleware(RequestDelegate next, ILogger logger){
_next = next;
_logger = logger;}publicasync Task Invoke(HttpContext context){var bodyStream = context.Response.Body;var responseBodyStream =newMemoryStream();
context.Response.Body = responseBodyStream;await_next(context);
responseBodyStream.Seek(0, SeekOrigin.Begin);var responseBody =newStreamReader(responseBodyStream).ReadToEnd();
_logger.LogInformation($"RESPONSE LOG: {responseBody}");
responseBodyStream.Seek(0, SeekOrigin.Begin);await responseBodyStream.CopyToAsync(bodyStream);}}
However, I get the error 'Cannot access a closed Stream' on the line
responseBodyStream.Seek(0, SeekOrigin.Begin);
Does anyone know how to do this?