title: Angular/Web API 2 returns invalid or corrupt file with StreamContent or ByteArrayContent
body: <p>I'm trying to return a file in a ASP.NET Web API Controller. This file is a dynamically-generated PDF saved in a MemoryStream.</p>
  
  <p>The client (browser) receives the file successfully, but when I open the file, I see that all the pages are totally blank.</p>
  
  <p>The thing is that if I take the same MemoryStream and write it to a file, this disk file is displayed correctly, so I assume that the problem is related to the file transfer via Web.</p>
  
  <p>My controller looks like this:</p>
  
  <pre><code>[HttpGet][Route("export/pdf")]
  public HttpResponseMessage ExportAsPdf()
  {
      MemoryStream memStream = new MemoryStream();
      PdfExporter.Instance.Generate(memStream);
  
      memStream.Position = 0;
      HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
      result.Content = new ByteArrayContent(memStream.ToArray()); //OR: new StreamContent(memStream);
      return result;
  }
  </code></pre>
  
  <p>Just to try, if I write the stream to disk, it's displayed correctly:</p>
  
  <pre><code>[HttpGet][Route("export/pdf")]
  public HttpResponseMessage ExportAsPdf()
  {
      MemoryStream memStream = new MemoryStream();
      PdfExporter.Instance.Generate(memStream);
  
      memStream.Position = 0;
      using (var fs = new FileStream("C:\\Temp\\test.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite))
      {
          memStream.CopyTo(fs);
      }
  
      return null;
  }
  </code></pre>
  
  <p>The differences are:</p>
  
  <ul>
  <li>PDF saved on disk: 34KB</li>
  <li>PDF transferred via web: 60KB (!)</li>
  </ul>
  
  <p>If I compare both files contents, the main differences are:</p>
  
  <p><a href="http://i.stack.imgur.com/Shfp0.png" rel="noreferrer">File Differences</a></p>
  
  <p>On the left is the PDF transferred via web; on the right, the PDF saved to disk.</p>
  
  <p>Is there something wrong with my code?
  Maybe something related to encodings?</p>
  
  <p>Thanks!</p>