I have a dotnet WebAPI what returns a Task<IActionResult>
returning OK(data)
- data
a is string which represents csv data. In Postman, this works perfectly - the response is shown in csv form in the result window and it shows that the type is text/plain: charset=utf-8
. In swagger same good result.
I now want to access this endpoint from an Angular front end app and enable the user to download it as a CSV. However, for some reason my http.post() crashes whenever I try to specify the content-type of the response... but if I don't specifiy it, I get back a CSV which has [object Object] in every cell. Even though the response type is text, it is still getting converted to JSON.
This is the CSV downloader code:
this.dataservice.downloadCSV().subscribe((response) => {
const data: Blob = new Blob([response], {
type: "text/csv; chartset-utf-8"});
saveAs(data, "filename.csv");
})
This seems to work ok... and then in the data service:
downloadCSV(inputParams): Observable<any>{
return this.http.post('https://localhost/getdata, inputParams)
}
This is gives a 200 success code, but ends up with [object Object] in every cell of the downloaded file... so somewhere it's turning back to JSON. So I thought in order to get the proper text result, I would do:
downloadCSV(inputParams): Observable<any>{
const headers = new HttpHeaders({
'Content-Type': 'text/plain: utf-8'
}),
return this.http.post('https://localhost/getdata,
inputParams,
httpOptions)
}
Edit: This is a bit closer, but even though the response type now comes as text and ends up in the CSV... it is all on row 1 and has [{ object parentheses and double quotes around all attributes...
I'm missing something somewhere...
Sorted.
There are numerous Stack threads recommending to do nothing but set 'Content-Type': 'text/plain'. But this is the type you are sending TO the api not the type you are expecting to get back from it.
In my case the content type is json, as I'm passing a json parameter object, then the response type is text.
So the code needed to look like this.
downloadCSV(inputParams): Observable<any>{
const headers = new HttpHeaders({
'Content-Type': 'application/json'
}),
return this.http.post('https://localhost/getdata,
inputParams,
{httpOptions, responseType: 'text'})
}