Attempting to download a .xlsx file using Angular 7 and web API in C#, encountering the following error:
https://i.sstatic.net/7pwDl.png
The code snippet from my service.ts is provided below:
public exportExcelFile(matchedRows: string, reportInfoId: number): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({ 'responseType': 'ResponseContentType.Blob',
'Content-Type': 'application/vnd.ms-excel'})};
const url = `${environment.apiUrl}report/${reportInfoId}/exportExcelFile?matchedRows=${matchedRows}`;
return this.http.get(url, httpOptions);
}
The method that utilizes my service:
exportExcelFile(matchedRows:string){
this.service.exportExcelFile(matchedRows, this.reportInfo.ide).subscribe((response)=>{
console.log(response)
})
this.exportingExcelFile=false;
this.ready=true;
}
The method responsible for retrieving response from the API:
[HttpGet]
public IHttpActionResult ExportExcelFile(int reportId, bool matchedRows)
{
var user = Request.GetAuthenticatedUser();
var query = new GetExcelFileQuery(reportId, user.UserName, matchedRows);
var result = _dispatcher.Dispatch<GetExcelFileQuery, GetExcelFileModel>(query);
using (var memoryStream = new MemoryStream()) //creating memoryStream
{
result.Workbook.Write(memoryStream);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(memoryStream.ToArray());
response.Content.Headers.ContentType = new MediaTypeHeaderValue
("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = result.FileName
};
return result == null ? NotFound() : (IHttpActionResult)new FileResult(response);
}
}
If accessing the URL directly through the browser, the excel file exports correctly.