Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to log response using middleware in aspnetcore Web API

$
0
0

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?


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>