I currently have a .net core 3.0 web api application connected to an angular 8 client. While I have successfully transferred data between them using json serialization, I am now looking for a way to transfer a bytes array from the api to the client.
After some research, I discovered that the recommended method to send binary data is through IActionResult instead of HttpResponseMessage. In my controller, I implemented the following code:
[HttpGet("Get-octetstream/{id}")]
public async Task<FileResult> GetAsOctetStream(int id)
{
var bytes= await GetData(id);
var stream = new MemoryStream(bytes);
return File(stream, "application/octet-stream", $"{id}.bin");
}
Upon testing, it worked perfectly fine as the data was saved in a file when accessed directly from the browser. The content was also correct.
However, when attempting to request this data from the Angular application:
async getOctetStreamFromServer(id: number) {
const url =
Utils.GetWebApiUrl() + `/misc/Get-octetstream/${id}`;
const currentUser = JSON.parse(sessionStorage.currentUser);
const myHttpOptions = {
headers: {
Authorization: "Bearer " + currentUser.jsonWebToken,
ResponseType: "blob",
},
};
const response = await this.httpClient.get(url, myHttpOptions).toPromise();
return response;
}
An error occurs:
ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":
{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost:11080/misc/
Get-octetstream/16588","ok":false,"name":"HttpErrorResponse","message":"Http failure during
parsing for http://localhost:11080/misc/Get-vxsor-octetstream/16588","error":{"error":
{},"text":"\u0011\u0...
I am seeking guidance on how to fetch binary data from a .NET Core web API service using TypeScript. Any assistance with providing a TypeScript code snippet would be greatly appreciated.