C#编写的WebApi接口直接返回byte数组引发的问题

如下面代码所示,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);           
}
相关推荐
刘梦凡呀15 小时前
C#获取钉钉平台考勤记录
java·c#·钉钉
承渊政道15 小时前
动态内存管理
c语言·c++·经验分享·c#·visual studio
future_studio15 小时前
聊聊 Unity(小白专享、C# 小程序 之 播放器)
unity·小程序·c#
helloworddm16 小时前
Orleans Stream SubscriptionId 生成机制详解
java·系统架构·c#
向宇it16 小时前
【unity实战】MapMagic 2实战例子
游戏·3d·unity·c#·游戏引擎
"菠萝"17 小时前
C#知识学习-017(修饰符_6)
学习·c#
VB.Net17 小时前
C#循序渐进
开发语言·c#
feifeigo12319 小时前
C# WinForms实现模拟叫号系统
c#
helloworddm19 小时前
Orleans 流系统握手机制时序图
后端·c#