如下面代码所示,C#编写的WebApi接口,本意是不做任何处理,直接将服务端生成的byte数组发送给客户端,但是在客户端接收时,无论是以字节数组形式接收,还是以字符串形式接收再解码都无法还原服务端发送的数据(如截图所示),如果是以字符串形式接收后将前面和后面的引号去掉再以base64解码则可以得到正确的字符串。
csharp
// 服务端代码
[HttpGet]
public byte[] GetBytes()
{
byte[] bytes = new byte[5];
bytes[0]= 0xFF;
bytes[1] = 0x01;
bytes[2] = 0x02;
bytes[3] = 0x03;
bytes[4] = 0x04;
return bytes;
}
客户端代码
byte[] result=client.GetByteArrayAsync(@"http://localhost:51789/EasyCaching/GetBytes").Result;
string strResult= client.GetStringAsync(@"http://localhost:51789/EasyCaching/GetBytes").Result;
byte[] resultBytes=Convert.FromBase64String(strResult.Trim('"'));
通过百度问题及查阅资料,定位问题为ASP.NET Code编写的WebApi接口默认将结果封装为json格式返回客户端,如果要将byte数组发送给客户端,可以采用以下2种方式(更多方式请自行百度或者咨询大模型):
1)以文件流形式返回数组;
csharp
[HttpGet]
public IActionResult GetBytes()
{
byte[] bytes = new byte[5];
bytes[0] = 0xFF;
bytes[1] = 0x01;
bytes[2] = 0x02;
bytes[3] = 0x03;
bytes[4] = 0x04;
return File(bytes, "application/octet-stream");
}
2)以base64形式将byte数组编码为字符串发送给客户端,客户端接收字符串后再解码:
csharp
[HttpGet]
public ActionResult<string> GetBytes()
{
byte[] bytes = new byte[5];
bytes[0] = 0xFF;
bytes[1] = 0x01;
bytes[2] = 0x02;
bytes[3] = 0x03;
bytes[4] = 0x04;
return Convert.ToBase64String(bytes);
}