0
votes

I am currently doing a POST to a Web Api method and am posting an array of objects. When I get to the method, my parameters are resolved properly, and I make a call to the DB and return a list of records.

I then take those records and convert them to a MemoryStream to be downloaded by the browser as an Excel spreasheet. From there, I create an HttpResponseMessage object and set properties so that the browser will recognize this response as a spreadsheet.

public HttpResponseMessage ExportSpreadsheet([FromBody]CustomWrapperClass request){
  var result = new HttpResponseMessage();

  var recordsFromDB = _service.GetRecords(request);

  MemoryStream export = recordsFromDB.ToExcel(); //custom ToExcel() extension method

  result.Content = new StreamContent(export);
  result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
  result.Content.Headers.ContentDisposition.Name = "formName";
  result.Content.Headers.ContentDisposition.FileName = "test.xlsx";

  return result;
}

Instead of seeing the spreadsheet being downloaded, nothing seems to happen. When I check the developer tools (for any browser), I see the Response Headers below while the Response tab just shows binary data. Does anyone know what I might be missing here?

enter image description here

1

1 Answers

0
votes

How are you doing your POST? It sounds like you might be trying to this via a javascript AJAX call, which cannot be done (https://stackoverflow.com/a/9970672/405180). I would instead make this a GET request for starters, and use something like window.location="download.action?para1=value1....". Generally web api Post requests are made to create a file/entry, not retrieve one. Alternatively, you could use a HTML Form with hidden elements corresponding to your query parameters, and use javascript to submit the form.