0

I'm trying to get an excel from the api, but eventhough I am setting it on the controller side, when it comes to the angular side, response doesn't have any content in it but headers.

This is how I'm setting the HttpResponseMessage on the Controller side:

HttpResponseMessage httpResponseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage package = new ExcelPackage();
using (package)
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("LIST of FILES");
    worksheet.Cells["A1"].LoadFromCollection(files);

    httpResponseMessage.Content = new ByteArrayContent(package.GetAsByteArray());
    httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    httpResponseMessage.Content.Headers.ContentDisposition.FileName = "EXCEL - "+ DateTime.Now.ToString();
    httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers
        .MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    httpResponseMessage.Content.Headers.Expires = DateTime.Now.AddMinutes(5);
}

return httpResponseMessage;

And this is how I send request to api:

  postWithApiUrl<T>(url: string, body: T): Promise<any> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
    });

    return new Promise((resolve, reject) => {
      this.http.post(url, body, { headers }).subscribe(response => {
         resolve(response);
      });
    });
  }

And I use this returned promise like this;

this.postWithApiUrl(url, this.req).then(response => {
      console.log(response);      
    });

This is how I receive the response:

console

Where am I making the mistake at?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
oividiosCaeremos
  • 608
  • 1
  • 10
  • 30
  • THat's not how `HttpResponseMessage` is used. It's not even needed if you simply want to return a file. `return File(package.GetAsByteArray(),"the-content-type")` is enough – Panagiotis Kanavos Nov 02 '20 at 13:31
  • BTW there are a lot of duplicates that show how to return an Excel file using EPPlus – Panagiotis Kanavos Nov 02 '20 at 13:32
  • Does this answer your question? [How do I return a generated XLSX using (Core 2.2) Web API?](https://stackoverflow.com/questions/57468979/how-do-i-return-a-generated-xlsx-using-core-2-2-web-api) – Panagiotis Kanavos Nov 02 '20 at 13:34
  • it didn't really work for me. returning `File` seems like not an option in my project, it gives error. – oividiosCaeremos Nov 02 '20 at 13:48
  • What kind of project are you building? ASP.NET Core Web API does have a `File` method. Are you [mixing up the Web API versions perhaps](https://stackoverflow.com/questions/42460198/return-file-in-asp-net-core-web-api) ? – Panagiotis Kanavos Nov 02 '20 at 15:39

0 Answers0