title: Response body for request/response Logging
body: <p>I'm trying to write a Owin midleware component that would LOG every incoming request and response to the database. </p>
  
  <p>Here's how far I managed to get. </p>
  
  <p>I got stuck on reading the response.body. Says:</p>
  
  <blockquote>
    <p>Stream does not support reading.</p>
  </blockquote>
  
  <p>How can I read the Response.Body ? </p>
  
  <pre><code> public class LoggingMiddleware : OwinMiddleware
   {
          private static Logger log = LogManager.GetLogger("WebApi");
  
          public LoggingMiddleware(OwinMiddleware next, IAppBuilder app)
              : base(next)
          {
          }
  
      public override async Task Invoke(IOwinContext context)
      {
          using (var db = new HermesEntities())
          {
  
              var sw = new Stopwatch();
              sw.Start();
  
              var logRequest = new log_Request
              {
                  Body = new StreamReader(context.Request.Body).ReadToEndAsync().Result,
                  Headers = Json.Encode(context.Request.Headers),
                  IPTo = context.Request.LocalIpAddress,
                  IpFrom = context.Request.RemoteIpAddress,
                  Method = context.Request.Method,
                  Service = "Api",
                  Uri = context.Request.Uri.ToString(),
                  UserName = context.Request.User.Identity.Name
  
              };
              db.log_Request.Add(logRequest);
              context.Request.Body.Position = 0;
  
              await Next.Invoke(context);
  
              var mem2 = new MemoryStream();
              await context.Response.Body.CopyToAsync(mem2);
  
              var logResponse = new log_Response
              {
                  Headers = Json.Encode(context.Response.Headers),
                  Body = new StreamReader(mem2).ReadToEndAsync().Result,
                  ProcessingTime = sw.Elapsed,
                  ResultCode = context.Response.StatusCode,
                  log_Request = logRequest
              };
  
              db.log_Response.Add(logResponse);
  
              await db.SaveChangesAsync();
          }
      }
  }
  </code></pre>