如何从 C# 中的 Web Api 方法正确获取字节数组? [英] How to Get byte array properly from an Web Api Method in C#?

查看:44
本文介绍了如何从 C# 中的 Web Api 方法正确获取字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下控制器方法:

[HttpPost]
[Route("SomeRoute")]
public byte[] MyMethod([FromBody] string ID)
{
  byte[] mybytearray = db.getmybytearray(ID);//working fine,returning proper result.
  return mybytearray;
}

现在在调用方法中(这也是另一个 WebApi 方法!)我是这样写的:

Now in the calling method(thats also another WebApi method!) I have written like this:

private HttpClient client = new HttpClient ();
private HttpResponseMessage response = new HttpResponseMessage ();
byte[] mybytearray = null;
response = client.GetAsync(string.Format("api/ABC/MyMethod/{0}", ID)).Result;
if (response.IsSuccessStatusCode)
{
    mybytearray = response.Content.ReadAsByteArrayAsync().Result;//Here is the problem
} 

现在,问题是发送的字节数组 MyMethod 是 528 字节,但是在制作 ReadAsByteArrayAsync 之后,大小变大(706 字节)并且值也被搞砸了.

Now, the problem is the byte array MyMethod is sending is of 528 bytes, but here after making ReadAsByteArrayAsync, the size becomes larger(706 bytes) and the values are also goofed up.

推荐答案

HTTP 是一种基于文本的协议.编辑:HTTP 也可以传输原始字节.Luaan的回答更好.

HTTP is a text based protocol. edit: HTTP can transport raw bytes as well. Luaan's answer is better.

返回的字节数组将以某种方式转换为文本,具体取决于 MediaTypeFormatterCollection 在服务器上的设置方式以及 HTTP 客户端使用 Accept<请求的格式/code> 标题.字节通常会通过 base64-encoding 转换为文本.响应也可能被进一步打包成 JSON 或 XML,但预期长度 (528) 与实际长度 (706) 的比率似乎表示一个简单的 base64 字符串.

The returned byte array will be converted into text in some way, depending on how the MediaTypeFormatterCollection is set up on the server and on the format requested by the HTTP client with the Accept header. The bytes will typically be converted to text by base64-encoding. The response may also be packaged further into JSON or XML, but the ratio of the expected length (528) to the actual length (706) seems to indicate a simple base64 string.

在客户端,您不是查看原始字节,而是查看此文本表示的字节.我会尝试使用 ReadAsStringAsync 将数据作为字符串读取并检查它以查看它的格式.还要查看响应的标题.

On the client side, you are not looking at the original bytes but at the bytes of this text representation. I would try reading the data as a string with ReadAsStringAsync and inspect it to see what format it is in. Also look at the headers of the response.

然后您应该相应地解析此文本以获取原始字节,例如使用 Convert.FromBase64String.

You should then parse this text accordingly to get the original bytes, e.g. with Convert.FromBase64String.

这篇关于如何从 C# 中的 Web Api 方法正确获取字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆