【发布时间】:2011-10-28 23:03:13
【问题描述】:
我需要提供一个文件下载功能,让 Web 服务器从另一个来源(通过 HTTP)检索文件并同时将其流式传输到浏览器。我猜使用MVC的Controller.File ActionResult是行不通的,但我还是写了一个这样的原型:
public ActionResult Download()
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://somewhere/somefile.pdf");
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
var mimeType = "application/pdf";
var fileName = "somefile.pdf";
return File(stream, mimeType, fileName);
}
这很好用,但是在 return 语句之后无法在 HttpWebResponse 和 Stream 上调用 Close()。 HttpWebResponse.GetResponseStream 方法上的help 说:“您必须调用 Stream.Close 或 HttpWebResponse.Close 方法来关闭流并释放连接以供重用。不必同时调用 Stream.Close 和 HttpWebResponse .Close,但这样做不会导致错误。未能关闭流将导致您的应用程序用尽连接。”
我是否应该按照this 或this 的行创建一个HttpHandler 并手动从源流中读取字节并将它们写入响应?还有其他我不知道的方法吗?
【问题讨论】:
-
根据this question,这种情况下框架会为你关闭流。
标签: asp.net-mvc download httphandler