title: how to return a xlsx file using memorystream web api
body: <p>I am successfully making a web request, creating xlsx file and saving it to a directory. I would like to stream it and return it to the client without actually saving it on the server. </p>
  
  <p>this is what i am currently using, it works fine</p>
  
  <pre><code>  private string generateStudyTemplate(string requestId)
      {
          var serviceUrl = ConfigurationManager.AppSettings["serviceUrl"];
  
          // create webRequest
          HttpWebRequest webRequest = createWebRequest(serviceUrl + "/" + requestId);
  
          // begin async call to web request
          IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
  
          // suspend this thread until call is complete. You might want to
          // do something usefull here like update your UI
          asyncResult.AsyncWaitHandle.WaitOne();
  
          // get the response from the completed web request
          var filename = string.Format("{0}.xlsx", "NewWorkbook");
          string physicalPath = HttpContext.Current.Server.MapPath("/FilesForExport");
          string relativePath = Path.Combine(physicalPath, filename).Replace("\\", "/");
          var filePath = relativePath;
  
         // var filePath = directory + "\\NewWorkbook.xlsx";
          using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
          {
              var str = webResponse.GetResponseStream();
              var inBuf = new byte[webResponse.ContentLength];
              var bytesToRead = Convert.ToInt32(inBuf.Length);
              var bytesRead = 0;
              while (bytesToRead &gt; 0)
              {
                  var n = str.Read(inBuf, bytesRead, bytesToRead);
                  if (n == 0)
                      break;
  
                  bytesRead += n;
                  bytesToRead -= n;
              }
  
              var fstr = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
              fstr.Write(inBuf, 0, bytesRead);
              fstr.Close();
          }
  
          return filePath;
      }
  
      private static HttpWebRequest createWebRequest(string url)
      {
          HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
          webRequest.ContentType = "text/xml;charset=\"utf-8\"";
          webRequest.Accept = "text/xml";
          webRequest.Method = "GET";
          return webRequest;
  }
  </code></pre>
  
  <p>Here is what I have put together from some other examples.</p>
  
  <pre><code> public HttpResponseMessage GenerateMarketStudyResult([FromBody]Result id)
      {
          if (id.requestId == null)
          {
              throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
          }
          var serviceUrl = ConfigurationManager.AppSettings["serviceUrl"];
  
          var streamContent = new PushStreamContent((outputStream, httpContext, transportContent) =&gt;
          {
              try
              {
                  HttpWebRequest webRequest = createWebRequest(serviceUrl + "/" + id.requestId);
                  IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
                  asyncResult.AsyncWaitHandle.WaitOne();
  
                  using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
                  {
                      using (MemoryStream memoryStream = new MemoryStream())
                      {
                          var str = webResponse.GetResponseStream();
                          var inBuf = new byte[webResponse.ContentLength];
                          var bytesToRead = Convert.ToInt32(inBuf.Length);
                          var bytesRead = 0;
                          while (bytesToRead &gt; 0)
                          {
                              var n = str.Read(inBuf, bytesRead, bytesToRead);
                              if (n == 0)
                                  break;
  
                              bytesRead += n;
                              bytesToRead -= n;
                          }
                          memoryStream.Write(inBuf, 0, bytesRead);
                      }
                  }
              }
              catch (Exception ex)
              {
                  Console.WriteLine(ex.Message);
              }
              finally
              {
                  outputStream.Close();
              }
          });
          streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
          streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
          streamContent.Headers.ContentDisposition.FileName = "reports.xlsx";
  
          var result = new HttpResponseMessage(HttpStatusCode.OK)
          {
              Content = streamContent
          };
          return result;
  
      }
  </code></pre>
  
  <p>I am not getting any exceptions, but the xlsx file is returning with 0bytes.</p>
  
  <p>The breakpoint here</p>
  
  <blockquote>
    <p>memoryStream.Write(inBuf, 0, bytesRead);</p>
  </blockquote>
  
  <p>here is the javascript serving the returned file</p>
  
  <pre><code>   $http.post('/api/GenerateMarketStudyResult/', Result, { responseType: 'arraybuffer' })
                     .success(function (response, status, headers, config) {
                         saveAs(new Blob([response], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }), 'reports.xlsx');
                     })
  </code></pre>
  
  <p>shows that the</p>
  
  <blockquote>
    <p>bytesRead = 112336</p>
  </blockquote>