【发布时间】:2017-06-19 10:19:22
【问题描述】:
我正在尝试从 WebAPI Rest Service 读取并返回文件内容,我正在 using.. 块内返回响应。我收到 System.ObjectDisposedException。有人可以帮我解决这个问题吗?
using (var fileStream = new FileStream(LocalFilePath, FileMode.Open))
{
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "MaxRecords.xls" };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
return response;
}
【问题讨论】:
-
那么不要使用“using”块?
-
删除 using 块是否有效?
response.Content正在引用已处置的实例 (fileStream)。 -
@DaveBecker 是的,它在删除 using 块后可以工作。但我希望使用块来处理文件流:(
-
不直接相关,但您是在创建真正的 Excel 文件还是通过返回扩展名为
xls的 CSV 或 HTML 文件来伪造它?这肯定会导致客户问题。xls在过去 10 年中已过时。您可以使用像 EPPlus 这样的库非常轻松地创建一个真正的 XLSX 文件,没有虚假内容或在服务器上安装 Excel
标签: c# asp.net asp.net-web-api asp.net-web-api2 idisposable