简体   繁体   English

C# 从 HTTPResposeMessage 获取字节数组

[英]C# Get Byte Array from HTTPResposeMessage

I have an API that returns a PDF file as a byte array:我有一个 API 将 PDF 文件作为字节数组返回:

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.此代码一直有效,直到升级到 .Net 5。

Now bytes is only <350 in length.现在字节的长度只有 <350。 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:我已经尝试将它从 base64 字符串转换为我在其他解决方案中阅读的内容,但这会引发错误,指出它不是有效的 base64 字符串:

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.这是替换后 base 的样子,下一行说它不是有效的 base64 字符串。 Looks like json but no byte array:看起来像 json 但没有字节数组:

{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?那么关于如何从响应中获取字节数组的任何想法?

The solution I got to work was instead of having the API return an HttpResponseMessage, have it return the byte array directly.我开始工作的解决方案不是让 API 返回一个 HttpResponseMessage,而是让它直接返回字节数组。

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.然后在客户端将它从 base64 字符串转换为我能够写为 PDF 的正确字节数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM