Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get Byte Array from HttpResposeMessage

I have an API that returns a PDF file as a byte array:

HttpResponseMessage fileResponse = new HttpResponseMessage
{
    Content = new ByteArrayContent(report) //here the byte array is >80000 in length
};
fileResponse.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
return fileResponse;

On the client, I have:

HttpResponseMessage result = null;
using (HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
    result = await client.GetAsync(getFileURL);
}
Byte[] bytes = response.Content.ReadAsByteArrayAsync().Result;

This code worked until an upgrade to .Net 5.

Now bytes is only <350 in length. I have tried converting it from a base64 string as I have read in other solutions, but that throws an error saying it is not a valid base64 string:

string base = response.Content.ReadAsStringAsync().Result.Replace("\"", string.Empty);
byte[] byte = Convert.FromBase64String(base);

Here's what base looks like after the replace, which the next line says is not a valid base64 string. Looks like json but no byte array:

{version:{major:1,minor:1,build:-1,revision:-1,majorRevision:-1,minorRevision:-1},content:{headers:[{key:Content-Type,value:[application/pdf]}]},statusCode:200,reasonPhrase:OK,headers:[],trailingHeaders:[],requestMessage:null,isSuccessStatusCode:true}

So any ideas on how to get the byte array out the response?

like image 907
J.Cart Avatar asked Jul 24 '26 22:07

J.Cart


1 Answers

The solution I got to work was instead of having the API return an HttpResponseMessage, have it return the byte array directly.

Then in the client converting it from a base64 string gave me the correct byte array that I was able to write as the PDF.

like image 70
J.Cart Avatar answered Jul 26 '26 10:07

J.Cart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!