title: Streaming large images using ASP.Net Webapi
body: <p>We are trying to return large image files using ASP.Net WebApi and using the following code to stream the bytes to the client.</p>
  
  <pre><code>public class RetrieveAssetController : ApiController
  {
      // GET api/retrieveasset/5
      public HttpResponseMessage GetAsset(int id)
      {
          HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
          string filePath = "SomeImageFile.jpg";
  
          MemoryStream memoryStream = new MemoryStream();
  
          FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  
          byte[] bytes = new byte[file.Length];
          file.Read(bytes, 0, (int)file.Length);
  
          memoryStream.Write(bytes, 0, (int)file.Length);
  
          file.Close();
  
          httpResponseMessage.Content =  new ByteArrayContent(memoryStream.ToArray());
          httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
          httpResponseMessage.StatusCode = HttpStatusCode.OK;
  
          return httpResponseMessage;
      }
  }
  </code></pre>
  
  <p>The above code works fine but some of the files that we deal with could be 2 GB and upwards in size resulting in connection timeouts.  We have used code similar to below in the past (using HttpHandlers) to chunk the response to the response stream to keep the connection alive with success. </p>
  
  <pre><code>byte[] b = new byte[this.BufferChunkSize];
  int byteCountRead = 0;
  
  while ((byteCountRead = stream.Read(b, 0, b.Length)) &gt; 0)
  {
      if (!response.IsClientConnected) break;
  
      response.OutputStream.Write(b, 0, byteCountRead);
      response.Flush();
  }
  </code></pre>
  
  <p>How can we use a similar technique using the new WebAPI programming model shown earlier?</p>