title: How can I safely intercept the Response stream in a custom Owin Middleware
body: <p>I'm trying to write a simple <a href="http://owin.org/">OWIN</a> Middleware, in order to intercept the response stream. What I'm trying to do is replace the original stream with custom Stream-based class, where I will be able to intercept writes to the response stream.</p>
  
  <p>However, I'm facing some issues because I cannot know when the response has been completely written to by inner middleware components in the chain. The <code>Dispose</code> override of the Stream is never called. So I don't know when it's time to perform my processing, which should happen at the end of the response Stream.</p>
  
  <p>Here is a sample code:</p>
  
  <pre><code>public sealed class CustomMiddleware: OwinMiddleware
  {
      public CustomMiddleware(OwinMiddleware next)
          : base(next)
      {
      }
  
      public override async Task Invoke(IOwinContext context)
      {
          var request = context.Request;
          var response = context.Response;
  
          // capture response stream
  
          var vr = new MemoryStream();
          var responseStream = new ResponseStream(vr, response.Body);
  
          response.OnSendingHeaders(state =&gt;
          {
              var resp = (state as IOwinContext).Response;
              var contentLength = resp.Headers.ContentLength;
  
              // contentLength == null for Chunked responses
  
          }, context);
  
          // invoke the next middleware in the pipeline
  
          await Next.Invoke(context);
      }
  }
  
  public sealed class ResponseStream : Stream
  {
      private readonly Stream stream_; // MemoryStream
      private readonly Stream output_; // Owin response
      private long writtenBytes_ = 0L;
  
      public ResponseStream(Stream stream, Stream output)
      {
          stream_ = stream;
          output_ = output;
      }
  
      ... // System.IO.Stream implementation
  
      public override void Write(byte[] buffer, int offset, int count)
      {
          // capture writes to the response stream in our local stream
          stream_.Write(buffer, offset, count);
  
          // write to the real output stream
          output_.Write(buffer, offset, count);
  
          // update the number of bytes written
  
          writtenBytes_ += count;
  
          // how do we know the response is complete ?
          // we could check that the number of bytes written
          // is equal to the content length, but content length
          // is not available for Chunked responses.
      }
  
      protected override void Dispose(bool disposing)
      {
          // we could perform our processing
          // when the stream is disposed of.
          // however, this method is never called by
          // the OWIN/Katana infrastructure.
      }
  }
  </code></pre>
  
  <p>As I've alluded to in the comments from the code above, there are two strategies that I can think of in order to detect whether the response is complete.</p>
  
  <p>a) I can record the number of bytes written to the response stream and correlate that to the expected response length. However, in the case of responses which use the Chunked Transfer Encoding, the length is not known.</p>
  
  <p>b) I can decide that the response stream is complete when <code>Dispose</code> is called on the response stream. However, the OWIN/Katana infrastructure never calls Dispose on the replaced stream.</p>
  
  <p>I have been investigating <a href="http://owin.org/spec/extensions/owin-OpaqueStream-Extension-v0.2.0.htm">Opaque Streaming</a> in order to see whether manipulating the underlying HTTP protocol would be a feasible approach, but I don't seem to find whether Katana supports Opaque Streaming or not.</p>
  
  <p>Is there a way to achieve what I want ?</p>