title: Setting Content-Length header in ASP.NET 5 response
body: <p><strong>TL; DR</strong> I have an ASP.NET 5 (MVC 6) application and just trying to set a HTTP Content-Length header in order to avoid chunked response.</p>
  
  <p>To my surprise, it happens that this is a quite tricky task to accomplish in ASP.NET 5. Everything is running on Kestrel which from ASP.NET 5 Beta7 <a href="http://blogs.msdn.com/b/webdev/archive/2015/09/02/announcing-availability-of-asp-net-5-beta7.aspx" rel="nofollow noreferrer">supports writing chunked responses automatically when no content length is specified for the response</a>.</p>
  
  <p>There is a similar question <a href="https://stackoverflow.com/questions/30652138/how-to-retrieve-the-current-response-body-length/31074575">here</a>, but the difference is that the OP just wants to count a response size, while I need to ensure that the Content-Length header is sent within a response. Tried with many things so far, and the only thing that works is writing a custom Middleware:</p>
  
  <pre><code>public class WebApiMiddleware {
      RequestDelegate _next;
  
      public WebApiMiddleware(RequestDelegate next) {
          _next = next;
      }
  
      public async Task Invoke(HttpContext context) {
           using (var buffer = new MemoryStream()) {
              var response = context.Response;
  
              var bodyStream = response.Body;
              response.Body = buffer;
  
              await _next(context);
  
              response.Headers.Add("Content-Length", new[] { buffer.Length.ToString()});
              buffer.Position = 0;
              await buffer.CopyToAsync(bodyStream);
          }
       }
  }
  </code></pre>
  
  <p>However, this is highly inefficient since we are using additional memory while processing every request. Using a custom stream that just wraps around the <code>context.Response.Body</code> stream and additionally counts bytes doesn't work since the Microsoft team states that <a href="https://github.com/aspnet/Home/issues/487#issuecomment-97695667" rel="nofollow noreferrer">once the amount of data they're willing to buffer has been written, it goes out on the wire and they don't store it any more</a>, so I can, at best, add Content-Length to the last chunk which is not the wished behavior - I want to avoid chunking completely.</p>
  
  <p>Any help is highly appreciated!</p>
  
  <p><em>p.s. I am aware that chunking is a regular feature of HTTP/1.1, but in my scenario it degrades performance so I want to avoid it without forcing the clients to send HTTP/1.0 requests.</em></p>