c# - c#在HttpResponseMessage中返回带有流(字节)的http内容
问题描述
我试图在 http 响应中返回一个流(实际上是字节数组)。我的第一种方法是
public async HttpResponseMessage GetBytes() {
// get a memory stream with bytes
using (var result = new HttpResponseMessage(HttpStatusCode.OK))
{
result.Content = new StreamContent(stream);
result.Content.Header.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
但是,在客户端(邮递员),我没有在 response.content 中看到二进制内容。它只有一个content header content-type application/octet-stream,但是长度不正确,基本上没有真正的字节。
然后我改用这种方法。
public async Task<ActionResult> GetBytes() {
// prepare the stream
return new FileContentResult(stream.ToBytes(), MediaTypeHeaderValue("application/octet-stream"));
}
这一次,它起作用了,我可以在客户端获取字节。为什么 HttpResponseMessage 不起作用?我认为如果我们可以使用 StreamContent 那么我们应该能够从内容中获取字节。这背后的逻辑是什么?
谢谢
解决方案
HttpResponseMessage
包含状态信息和请求数据。必须使用Content
in 属性HttpResponseMessage
返回数据
public async Task<HttpContent> GetBytes() {
// get a memory stream with bytes
using (var result = new HttpResponseMessage(HttpStatusCode.OK))
{
result.Content = new StreamContent(stream);
result.Content.Header.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result.Content;
}
}
推荐阅读
- node.js - 分配给顺序数组的异步结果
- python - ModuleNotFoundError:没有名为“tkSimpleDialog”的模块 - Python Shell
- keras - 在 keras 中如何调用 add 函数 [a3,a8]
- android - 为什么 Webview 更改语言
- sql-server - 表关系 - 最佳实践
- python - 如何多次编辑附加到列表中的行?
- javascript - 由于 Promise 链接,Firebase Firestore 更新查询不会执行。我究竟做错了什么?
- linux - 面临 ORA-01033:由于数据文件问题,ORACLE 初始化或关闭正在进行中
- javascript - Meteor 应用程序部署后的代码覆盖率
- android - ContryCodePicker 在组件树中显示为问号