title: Downloading excel file using MVC 5 and WebAPI
body: <p>Here's what I'm using: AngularJS, BreezeJS on the client side. For the server, I'm using Web API and MVC 5.</p>
  
  <p>I've been searching for ways on how to build and retrieve an excel spreadsheet from the server, but I'm at a loss.</p>
  
  <p>I found this plugin called linqtocsv that helps greatly in building the csv file out of linq. The codeproject example is found <a href="http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library" rel="nofollow noreferrer">here</a> and the nuget link is found <a href="https://www.nuget.org/packages/LinqToCsv" rel="nofollow noreferrer">here</a>.</p>
  
  <p>I also found nice useage on a question on stackover flow: <a href="https://stackoverflow.com/questions/19965792/web-api-httpresponsemessage-content-return-is-incomplete">Web API HttpResponseMessage content return is incomplete</a></p>
  
  <p>So after implementing the above plugin - linq to csv, and following the mentioned stackover question, nothing seems to be working.</p>
  
  <p>Here is my server side code (both taken directly from the link mentioned already):</p>
  
  <pre><code>    [HttpPost]
      public HttpResponseMessage DistributorReport(JObject formValues)
      {
          try
          {
              var cqmo = formValues.ToObject&lt;DistributorCQMO&gt;();
  
              var query = new FindDistributorsByLocationQuery
              {
                  States = cqmo.States.Select(x =&gt; x.id),
                  Cities = cqmo.Cities.Select(x =&gt; x.id),
                  CitiesExclusion = cqmo.ExcludedCities.Select(x =&gt; x.id),
                  ZipCodes = cqmo.ZipCodes.Select(x =&gt; x.id),
                  ZipCodesExclusion = cqmo.ExcludedZipCodes.Select(x =&gt; x.id),
                  ProductFamily = cqmo.ProductFamily.id,
                  ProductSubFamilies = cqmo.ProductSubFamily.Select(x =&gt; x.id),
                  MatchAllFilter = cqmo.MatchAllFilter,
                  ClientTypeFilter = cqmo.ClientTypeFilter
              };
  
  
  
              IEnumerable&lt;DistributorDTO&gt; distributors = this.queryProcessor.Process(query).AsQueryable();
  
              CsvFileDescription outputFileDescription = new CsvFileDescription
              {
                  SeparatorChar = '\t', // tab delimited
                  FirstLineHasColumnNames = true
              };
  
  
              HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK)
              {
                  Content = new CsvContent&lt;DistributorDTO&gt;(outputFileDescription,
                                                             "ObserverTripList.csv",
                                                              distributors)
              };
  
              return response;
  
          }  
          catch (Exception ex)  
          {  
              // logger.ErrorException("Exception exporting as excel file: ", ex);  
              return Request.CreateResponse(HttpStatusCode.InternalServerError);  
          } 
      }
  </code></pre>
  
  <p>and here's the helper class:</p>
  
  <pre><code>public class CsvContent&lt;T&gt; : HttpContent
  {
      private readonly MemoryStream _stream = new MemoryStream();
      public CsvContent(CsvFileDescription outputFileDescription, string filename, IEnumerable&lt;T&gt; data)
      {
          var cc = new CsvContext();
          var writer = new StreamWriter(_stream);
          cc.Write(data, writer, outputFileDescription);
          writer.Flush();
          _stream.Position = 0;
  
          Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
          Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
          Headers.ContentDisposition.FileName = filename;
  
      }
      protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
      {
          return _stream.CopyToAsync(stream);
      }
  
      protected override bool TryComputeLength(out long length)
      {
          length = _stream.Length;
          return true;
      }
  }
  </code></pre>
  
  <p>I tried using breeze to make my post, which returns the data wrapped up in the breeze object, and if after digging into the returned object, into it's httpreponse property, you'll see in its raw form, the tabbed delimited data, however, the content application is in application/json; charset=utf-8 and not of excel formatting.</p>
  
  <p>EDIT:</p>
  
  <p>I have the following now working:</p>
  
  <pre><code>    $.ajax({
          type: 'POST',
          url: 'MappingTool.API/api/Report/DistributorReport',
          data: JSON.stringify(jsonData),
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          success: function (returnValue) {
              alert("success")
             // window.location = '/Reports/Download?file=' + returnValue;
              }
      });
  </code></pre>
  
  <p>I'm getting the correct response and able to view all the results in fiddler and in chrome debugger. But how do I get the browser to download the file automatically?</p>
  
  <p>any feedback is appreciated!</p>
  
  <p>Edit:</p>
  
  <p>Is this something that I should be fetching from an MVC controller or an API controller? It seems there is more support for an MVC controller, like the FileResult type that can be used in MVC; which would give me my automatic download: "<a href="https://stackoverflow.com/questions/7623599/exporting-excel-file-to-view-mvc">exporting excel file to view mvc</a>" I've seen it being done using an API controller; but isn't the point of an API controller to delegate simple data types, and not media content?</p>