title: How to download CSV file from ASP.NET Web Api using jQuery Ajax call
body: <p>I am working on how to download CSV file from ASP.NET Web Api from jQuery ajax call. The CSV file is generated dynamically from Web API server based on custom CsvFormatter.</p>
  
  <p>Ajax from jQuery:</p>
  
  <pre><code>   $.ajax({
          type: "GET",
          headers: {
              Accept: "text/csv; charset=utf-8",
          },
          url: "/api/employees",
          success: function (data) {
          }
      });
  </code></pre>
  
  <p>On the server, the <code>EmployeeCsvFormatter</code> is implemented similar with below article, derived from <code>BufferedMediaTypeFormatter</code>:</p>
  
  <p><a href="http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters">http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters</a></p>
  
  <pre><code>public class EmployeeCsvFormatter : BufferedMediaTypeFormatter
  {
      public EmployeeCsvFormatter()
      {
          SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
      }
      ...
  }
  </code></pre>
  
  <p>I also added override method to indicate that I would like to download like normal way to download file (can see the download file in download tab):</p>
  
  <pre><code> public override void SetDefaultContentHeaders(Type type, 
      HttpContentHeaders headers, MediaTypeHeaderValue mediaType)       
  {
      base.SetDefaultContentHeaders(type, headers, mediaType);
      headers.Add("Content-Disposition", "attachment; filename=yourname.csv");
      headers.ContentType =  new MediaTypeHeaderValue("application/octet-stream");
  }
  </code></pre>
  
  <p>But it does not work, the download file does not showed in status bar or in download tab on Chrome, even though from Fiddler, I see it the response seems correct:</p>
  
  <pre><code>HTTP/1.1 200 OK
  Server: ASP.NET Development Server/11.0.0.0
  Date: Mon, 11 Mar 2013 08:19:35 GMT
  X-AspNet-Version: 4.0.30319
  Content-Disposition: attachment; filename=yourname.csv
  Cache-Control: no-cache
  Pragma: no-cache
  Expires: -1
  Content-Type: application/octet-stream
  Content-Length: 26
  Connection: Close
  
  1,Cuong,123
  1,Trung,123
  </code></pre>
  
  <p>My method from ApiController:</p>
  
  <pre><code>public EmployeeDto[] Get()
  {
      var result = new[]
                 {
                     new EmployeeDto() {Id = 1, Name = "Cuong", Address = "123"},
                     new EmployeeDto() {Id = 1, Name = "Trung", Address = "123"},
                 };
  
      return result;
  }
  </code></pre>
  
  <p>It must be wrong somewhere which I have not figured out. How can I make it work by downloading CSV file like normal way?</p>