首页 > 解决方案 > 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 那么我们应该能够从内容中获取字节。这背后的逻辑是什么?

谢谢

标签: c#asp.netasp.net-mvchttp

解决方案


HttpResponseMessage包含状态信息和请求数据。必须使用Contentin 属性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;
    }
}

推荐阅读