我们正在尝试使用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;
}
}
以上代码运行良好,但我们处理的一些文件可能会超过2GB大小,从而导致连接超时。我们过去曾经使用类似以下的代码(使用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编程模型来使用类似的技术?