4

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?

4
  • 1
    Looks like the default now is HTTP/2. Not sure what is broken. Need to do more research. See : learn.microsoft.com/en-us/aspnet/core/release-notes/… Commented Mar 11, 2021 at 17:05
  • 2
    response.Content.ReadAsByteArrayAsync().Result should be result? Does fileResponse contain all the bytes in your API? Where/how are you determining you have <350? Commented Mar 11, 2021 at 17:06
  • @mxmissile ya sorry that's a typo Commented Mar 11, 2021 at 17:11
  • 1
    See following : devblogs.microsoft.com/dotnet/net-5-new-networking-improvements/… Commented Mar 11, 2021 at 17:13

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.