我正在尝试从我的 ASP.NET Core 2 Controller 返回一个 PDF 文件。 我有这个代码 (主要是从这个 SO question 借来的):
var net = new System.Net.WebClient();
//a random pdf file link
var fileLocation = "https://syntera.io/documents/T&C.pdf";/
var data = net.DownloadData(fileLocation);
MemoryStream content = null;
try
{
content = new MemoryStream(data);
return new FileStreamResult(content, "Application/octet-stream");
}
finally
{
content?.Dispose();
}
上面的代码是我的 Controller 调用的服务类的一部分。这是来 self 的 Controller 的代码。
public async Task<IActionResult> DownloadFile(string fileName)
{
var result = await _downloader.DownloadFileAsync(fileName);
return result;
}
但我不断收到 ObjectDisposedException: Cannot access a closed Stream.
try 和 finally block 是试图修复它,来自另一个 SO 问题。
主要问题是 A) 这是将 PDF 文件发送回浏览器的正确方法吗?B) 如果不是,我如何更改代码以将 pdf 文件发送到浏览器?
理想情况下,我不想先将文件保存在服务器上,然后再将其返回给 Controller 。我宁愿在将所有内容都保存在内存中的同时归还它。
最佳答案
finally
总是会被调用(甚至在 return
之后)所以它总是会在发送之前处理内容流给客户端,因此出现错误。
Ideally , I don't want to first save the file on the server and then return it to the controller. I'd rather return it while keeping everything in memory.
使用 FileContentResult
类获取原始字节数组数据并直接返回它。
FileContentResult: Represents an
ActionResult
that when executed will write a binary file to the response.
async Task<IActionResult> DownloadFileAsync(string fileName){
using(var net = new System.Net.WebClient()) {
byte[] data = await net.DownloadDataTaskAsync(fileName);
return new FileContentResult(data, "application/pdf") {
FileDownloadName = "file_name_here.pdf"
};
}
}
不需要额外的内存流
关于c# - 从 ASP.NET Core 2 Controller 返回 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52127108/