title: Dot net core Middleware : How to read response message
body: <p>I am using custom middleware to log error and warning messages in a dotnet core application. I am able to read the status code but am stuck at reading the http response message. Below is the code : </p>
  
  <p>Code from Controller which returns a bad request : </p>
  
  <pre><code>return BadRequest(errorModel);
  </code></pre>
  
  <p>Middleware code to log errors : </p>
  
  <pre><code> public async Task Invoke(HttpContext context)
      {
          try
          {
              await _next(context);
  
              // Log Bad Request 
              // log anything outside this
              if (context.Response.StatusCode != StatusCodes.Status200OK &amp;&amp;
                  context.Response.StatusCode != StatusCodes.Status201Created 
               &amp;&amp;
                  context.Response.StatusCode != StatusCodes.Status202Accepted
                  )
              {
                  var reponseBodyStream = new MemoryStream();
                  var originalResponseBody = context.Response.Body;
                  await originalResponseBody.CopyToAsync(reponseBodyStream);
                  reponseBodyStream.Seek(0, SeekOrigin.Begin);
                  var requestBodyText = new 
                  StreamReader(reponseBodyStream).ReadToEnd();
              }
          }
  </code></pre>
  
  <p>The response body is null here. It is not readable as well. Error is obtained at the point where i am copying response stream into other stream.What is wrong with this code and how to read the response message?</p>