首页 > 解决方案 > 如何以正确的方式通过 http 发送二进制数据?

问题描述

我在 C# 中有以下代码,它将字符串从一种编码转换为另一种编码,并通过 http 发送响应。

代码中的一切工作正常。我只是有点困惑

当我通过 http 返回它时,它会转换为文本表示形式。我以为这只会发送原始字节数组?

为什么要转换?我应该永远不要尝试发送原始字节数组,还是在通过 http 通信时有这种情况?或者是文本表示和application/octet-stream通过http发送二进制数据的方式?

byte[] fromBytes = fromEncoding.GetBytes(body);
byte[] toBytes = Encoding.Convert(fromEncoding, toEncoding, fromBytes);

var response = req.CreateResponse(HttpStatusCode.OK);
MemoryStream ms = new MemoryStream(toBytes);
response.Content = new StreamContent(ms);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;

标签: c#.nethttp

解决方案


推荐阅读