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);           
}
相关推荐
EIP低代码平台2 小时前
EIP 低代码平台 - 角色维护
低代码·c#·权限·工作流·netcore
心平气和量大福大6 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
-银雾鸢尾-10 小时前
C#中HashTable相关方法
开发语言·c#
geovindu14 小时前
CSharp: Flyweight Pattern
开发语言·后端·c#·.net·享元模式·结构型模式
吴可可12314 小时前
C# CAD二次开发中如何退出窗口
c#
影寂ldy15 小时前
C# WinForm 三种自定义控件 + 完全自定义重绘控件知识点
开发语言·c#
ellis197015 小时前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#
-银雾鸢尾-15 小时前
C#中的Dictionary相关方法
开发语言·c#
lzhdim15 小时前
C# 中读取CPU、硬盘和内存温度
开发语言·c#
WarPigs16 小时前
.NET项目app.Config笔记
c#·.net