我们正在尝试使用 ASP.Net WebApi 返回大型图像文件,并使用以下代码将字节流式传输到客户端。
public class RetrieveAssetController : ApiController
{
// GET api/retrieveasset/5
public HttpResponseMessage GetAsset(int id)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
string filePath = "SomeImageFile.jpg";
MemoryStream memoryStream = new MemoryStream();
FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
memoryStream.Write(bytes, 0, (int)file.Length);
file.Close();
httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
}
上面的代码工作正常,但我们处理的一些文件的大小可能为 2 GB 或更大,从而导致连接超时。我们过去使用类似于下面的代码(使用 HttpHandlers)将响应分块到响应流,以保持连接成功。
byte[] b = new byte[this.BufferChunkSize];
int byteCountRead = 0;
while ((byteCountRead = stream.Read(b, 0, b.Length)) > 0)
{
if (!response.IsClientConnected) break;
response.OutputStream.Write(b, 0, byteCountRead);
response.Flush();
}
我们如何通过前面展示的新 WebAPI 编程模型来使用类似的技术?
最佳答案
是的,您可以使用 PushStreamContent
。如果您将它与异步执行(使用异步 lambda)相结合,您可能会获得更有效的结果。
本月早些时候,我在博客中介绍了这种方法 - http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/ .
例子中使用的是视频文件,原理是一样的——将字节数据下推给客户端。
关于c# - 使用 ASP.Net Webapi 流式传输大图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14697497/