我试图在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;
}
}
然而,在客户端(Postman),我没有在response.content中看到二进制内容。它只有一个内容头内容类型的应用程序/octet-stream,但长度不正确,基本上真正的字节不在那里。
然后我切换到这个方法。
public async Task<ActionResult> GetBytes() {
// prepare the stream
return new FileContentResult(stream.ToBytes(), MediaTypeHeaderValue("application/octet-stream"));
}
这一次,它工作了,我可以在客户端获得字节。为什么HttpResponseMessage不工作?我认为如果我们可以使用流内容,那么我们应该能够从内容中获得字节。这背后的逻辑是什么?
感谢HttpResponseMessage
包含状态信息和请求数据。必须在HttpResponseMessage
中使用Content
属性来返回数据
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;
}
}