title: Logging response body BEFORE compression in ASP.Net Core
body: <p>I have a seemingly simple thing that I need to do; log the response body from middleware AFTER it has been fully formed by controllers but BEFORE compression is applied.</p>
  <p>The problem here is that I am only able to read a response after awaiting next() from the logging middleware, which also compresses the response body.</p>
  <p>My logging implementation is based on this article;
  <a href="https://elanderson.net/2019/12/log-requests-and-responses-in-asp-net-core-3/?unapproved=220252&amp;moderation-hash=337bbb1489547696340e7506459779ba#comment-220252" rel="nofollow noreferrer">https://elanderson.net/2019/12/log-requests-and-responses-in-asp-net-core-3/?unapproved=220252&amp;moderation-hash=337bbb1489547696340e7506459779ba#comment-220252</a></p>
  <pre><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
  ...
      app.UseMiddleware&lt;RequestResponseLoggingMiddleware&gt;();
  
      app.UseRouting();
  
      //compression
      app.UseResponseCompression();
  
      app.UseAuthentication();
      app.UseAuthorization();
  
      app.UseEndpoints(endpoints =&gt; {
          endpoints.MapControllers();
      });
  
      ConfigurePSTZone();
  ...
  }
  </code></pre>
  <p>RequestResponseLoggingMiddleware middleware;</p>
  <pre><code>    var originalBodyStream = context.Response.Body;
      await using var responseBody = _recyclableMemoryStreamManager.GetStream();
      context.Response.Body = responseBody;
      await _next(context); 
      context.Response.Body.Seek(0, SeekOrigin.Begin);
      var responseBody = await new StreamReader(context.Response.Body).ReadToEndAsync();
  </code></pre>
  <p>If you call <strong>await _next(context);</strong> then responseBody will be filled with the compressed response after. If you dont call it, responseBody will be empty. Even if you move the <strong>UseMiddleware();</strong> to the very end of Configure.</p>
  <p>Not sure there is actually a solution for this currently in .Net 5, but hey maybe someone has figured it out.</p>
  <p>Thanks</p>
  <p><strong>ADDED NOTE:</strong> This seems to only be a problem when using Asp.Net with kestrel (linux based). On windows you dont need response compression middleware.. so I guess not a lot of people have switched to Linux yet which is why nobody has asked this question before. Jeepers</p>