title: Cannot download a file from MVC Controller talks to Web Api Download File
body: <p>I have a Asp.Net WebApi and a Asp.Net MVC Web project. Web Api provides file download function. Browser requests the DownloadController in MVC WebClient which talks to Web Api File download controller.</p>
  
  <p>I referred to <a href="http://arcware.net/upload-and-download-files-with-web-api-and-azure-blob-storage/" rel="nofollow">this</a> article to implement file download to the WebApi.(I trid to call the web api directly from the browser as mentioned in the example and it worked). But in my case I need to send the file to the browser via the MVC Web App. 
  I get the memory stream to the Webserver (MVC Controller), and in the WebServer temp folder (C:\Temp folder), it creates a file but the size is 0kb and It cannot be opened (Cannot read the file, some process is using it). When IIS is restarted, it gives the error "Format exception: Not a valid PDF or corrupted".  </p>
  
  <p>Browser gets a Download Pdf and it says Loading, but never completes. </p>
  
  <p>I am keeping the Memory stream open until the file download completes in the Web Api. Otherwise I get a null response from Web Api to Web server. </p>
  
  <p>Am I doing something which is not recommended? What is the best way to handle this scenario?</p>
  
  <p>Here is the code,</p>
  
  <p>Web Api project, Download file function</p>
  
  <pre><code> public HttpResponseMessage GetById(string fileid)
   {         
            //fileid = e.g. &lt;someguid&gt;.pdf
          try
          {                                
            var result = DownloadBlob(fileid);
  
            if (result == null)
            {
               return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
  
           result.BlobStream.Position = 0;
           return Request.CreateResponse(HttpStatusCode.OK, result);
  
        }
     }
  </code></pre>
  
  <p>MVC Web App (talks to Web Api and needs to send file response)</p>
  
  <pre><code>public async Task&lt;FileStreamResult&gt; DownloadInvoice()
          {
              string id = "6bc7fb58-4bd3-4a09-bd90-98a837d4e441.pdf";
  
              //Call WebApiClient
              BcxApiConfiguration config = new BcxApiConfiguration();//This will load settings. These settings will be used in HMAC
              BcxBillingApi&lt;BcxInvoiceFile&gt; invoiceApi = new BcxBillingApi&lt;BcxInvoiceFile&gt;(config.Uri, config.AppId, config.ApiKey, organisationId);
  
              BcxInvoiceFile result = await invoiceApi.GetByIdAsync(id);
  
              //WRITE TO FILE
              string path = @"C:\Temp\" + result.BlobFileName;
              var fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite);
  
              fileStream.Position = 0;
              fileStream.CopyTo(result.BlobStream);
  
              return new FileStreamResult(fileStream, "application/pdf");
  
          }
  </code></pre>
  
  <p>Download Helper in Web Api,</p>
  
  <pre><code>public BcxInvoiceFile DownloadBlob(string blobFileId)
  {
              var billingFileInstanceFileName = String.Empty;
              string destFile;
              // Retrieve storage account from connection string.
              var storageAccount = CloudStorageAccount.Parse(StorageAccountConnectionString);
  
              // Create the blob client.
              var blobClient = storageAccount.CreateCloudBlobClient();
  
              // Retrieve Storage container.
              var container = blobClient.GetContainerReference(StorageContainer);
  
              // Create the container if it doesn't already exist.
              container.CreateIfNotExists();
  
  
              // Retrieve Blob Reference.
              var blockBlob = container.GetBlockBlobReference(blobFileId);           
  
              string text;
              var memoryStream = new MemoryStream();
              blockBlob.DownloadToStream(memoryStream);
              text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
  
              // Strip off any folder structure so the file name is just the file name
              var lastPos = blockBlob.Name.LastIndexOf('/');
              var fileName = blockBlob.Name.Substring(lastPos + 1, blockBlob.Name.Length - lastPos - 1);
  
              // Build and return the download model with the blob stream and its relevant info
              var download = new BcxInvoiceFile
              {
                  BlobStream = memoryStream,
                  BlobFileName = fileName,
                  BlobLength = blockBlob.Properties.Length,
                  BlobContentType = blockBlob.Properties.ContentType
              };
  
              return download;
  
              // return billingFileInstanceFileName;
   }
  </code></pre>
  
  <p>Model class for file download,</p>
  
  <pre><code> public class BcxInvoiceFile
   {
          public MemoryStream BlobStream { get; set; }
          public string BlobFileName { get; set; }
          public string BlobContentType { get; set; }
          public long BlobLength { get; set; }
   }
  </code></pre>