我正在尝试从我的 ASP.NET Core 2 控制器返回一个 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();
}
Run Code Online (Sandbox Code Playgroud)
上面的代码是我的控制器调用的服务类的一部分。这是来自我的控制器的代码。
public async Task<IActionResult> DownloadFile(string fileName)
{
var result = await _downloader.DownloadFileAsync(fileName);
return result;
}
Run Code Online (Sandbox Code Playgroud)
但我不断得到 ObjectDisposedException: Cannot access a closed Stream.
try 和 finally 块是尝试修复它,来自另一个 SO 问题。
主要问题是 A) 这是将 PDF 文件发送回浏览器的正确方法,B) …