c# - 从 ASP.NET Core 2 Controller 返回 PDF

标签 c# asp.net-core

我正在尝试从我的 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/

相关文章:

c# - DataContext 没有在带有路径数据的自定义按钮中设置

c# - 如何在长时间循环期间使用服务器端变量更新客户端?

c# - Model-View-Presenter 模式中 "View"的用途是什么?

c# - 创建文件夹结构,每个文件夹包含 x 个文件

c# - 在不使用 IDataProtector 的情况下,在 ASP.NET Core 中加密 cookie 的简单/体面的方法是什么?

iis - 如何有条件地在 IIS 中禁用 Keep-Alive?

C# 序列化从 sqlite 返回的 DataTable 结果正在返回 XML 格式

c# - 使用 .NET 核心中的 dapper 批量插入 PostgreSQL

c# - 如何在缓存中存储数据?

asp.net-core - 如何更改基本网址?