title: Logging raw and compressed HTTP responses in ASP.NET & IIS7
body: <p>Along the lines of <a href="https://stackoverflow.com/questions/1038466/logging-raw-http-request-response-in-asp-net-mvc-iis7">this question</a> I want to create a HttpModule that will do some custom logging of requests and responses for us. Using the code in the most popular answer for that question I've got a HttpModule up and running which does indeed work:</p>
  
  <pre><code>class PortalTrafficModule : IHttpModule
  {
      public void Dispose()
      {
          // Do Nothing
      }
  
      public void Init(HttpApplication context)
      {
          context.BeginRequest += new EventHandler(context_BeginRequest);
          context.EndRequest += new EventHandler(context_EndRequest);
      }
  
      private void context_BeginRequest(object sender, EventArgs e)
      {
          HttpContext context = ((HttpApplication)sender).Context;
  
          // Create and attach the OutputFilterStream to the Response and store it for later retrieval.
          OutputFilterStream filter = new OutputFilterStream(context.Response.Filter);
          context.Response.Filter = filter;
          context.Items.Add("OutputFilter", filter);
  
          // TODO: If required the request headers and content could be recorded here
      }
  
      private void context_EndRequest(object sender, EventArgs e)
      {
          HttpContext context = ((HttpApplication)sender).Context;
          OutputFilterStream filter = context.Items["OutputFilter"] as OutputFilterStream;
  
          if (filter != null)
          {
              // TODO: Log here - for now just debug.
              Debug.WriteLine("{0},{1},{2}",
                  context.Response.Status,
                  context.Request.Path,
                  filter.ReadStream().Length);
          }
      }
  }
  </code></pre>
  
  <p><em>(note that the OutputFilterStream class referred to in the code is in the referenced <a href="https://stackoverflow.com/questions/1038466/logging-raw-http-request-response-in-asp-net-mvc-iis7">question</a>).</em></p>
  
  <p>However, the responses seem to be missing some HTTP headers that I see in Fiddler (like "Date") and more importantly, when I turn on compression the responses I'm logging aren't compressed whereas what I see in Fiddler is.</p>
  
  <p><strong>So my question</strong> - is it possible to log the compressed content or is this happening in a subsequent step my module can't hook in to?</p>
  
  <p>For the record, I've also tried handling the <em>PreSendRequestContent</em> event and the response is still uncompressed.</p>