title: How to read the HttpResponse Body?
body: <p>I have a .NET Core Web API project with a request and response logging middleware. I registered both middleware files in the <code>Configure</code> method in the <code>Startup</code> file</p>
  <pre><code>app.UseMiddleware&lt;RequestLoggingMiddleware&gt;();
  app.UseMiddleware&lt;ResponseLoggingMiddleware&gt;();
  </code></pre>
  <p>For now I'm just trying to log the body, the request logging seems to work fine</p>
  <pre><code>public class RequestLoggingMiddleware
  {
      private readonly RequestDelegate requestDelegate;
  
      public RequestLoggingMiddleware(RequestDelegate requestDelegate)
      {
          this.requestDelegate = requestDelegate;
      }
  
      public async Task InvokeAsync(HttpContext httpContext)
      {
          HttpRequest httpRequest = httpContext.Request;
          httpRequest.EnableBuffering();
  
          ReadResult bodyReadResult = await httpRequest.BodyReader.ReadAsync();
          ReadOnlySequence&lt;byte&gt; bodyBuffer = bodyReadResult.Buffer;
  
          if (bodyBuffer.Length &gt; 0)
          {
              byte[] bodyBytes = bodyBuffer.ToArray();
              string bodyText = Encoding.UTF8.GetString(bodyBytes);
  
              Console.WriteLine(bodyText);
          }
  
          // Reset
          httpRequest.Body.Seek(0, SeekOrigin.Begin);
  
          await requestDelegate(httpContext);
      }
  }
  </code></pre>
  <p>My response logging middleware does not have access to a <code>BodyReader</code>. I tried to go with this code</p>
  <pre><code>public class ResponseLoggingMiddleware
  {
      private readonly RequestDelegate requestDelegate;
  
      public ResponseLoggingMiddleware(RequestDelegate requestDelegate)
      {
          this.requestDelegate = requestDelegate;
      }
  
      public async Task InvokeAsync(HttpContext httpContext)
      {
          await requestDelegate(httpContext);
  
          Stream responseBody = httpContext.Response.Body;
  
          using (StreamReader reader = new StreamReader(responseBody))
          {
              string bodyText = await reader.ReadToEndAsync();
  
              // Reset
              responseBody.Seek(0, SeekOrigin.Begin);
  
              Console.WriteLine(bodyText);
          }
      }
  }
  </code></pre>
  <p>but unfortunately I get this exception</p>
  <blockquote>
  <p>System.ArgumentException: Stream was not readable.</p>
  </blockquote>
  <p>Does someone know how to fix it?</p>