raj*_*raj 16 c# streaming download large-files asp.net-web-api
我们正在尝试使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常但我们处理的一些文件可能是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();
}
Run Code Online (Sandbox Code Playgroud)
我们如何使用前面显示的新WebAPI编程模型使用类似的技术?
先感谢您
Fil*_*p W 26
是的,你可以使用PushStreamContent.如果将它与异步执行(即async lambdas)结合使用,您可能会获得更有效的结果.
我本月早些时候在博客上写过这种方法 - http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/.
该示例使用了视频文件,原理相同 - 将数据字节向下推送到客户端.
| 归档时间: |
|
| 查看次数: |
20755 次 |
| 最近记录: |