+-
从ASP.NET Core 2控制器返回PDF
我试图从我的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();
}

上面的代码是我的控制器调用的服务类的一部分.这是我控制器的代码.

public async Task<IActionResult> DownloadFile(string fileName)
{
    var result = await _downloader.DownloadFileAsync(fileName);
    return result;
}

但是我一直在获取ObjectDisposedException:无法访问封闭的Stream.

try and finally块是从另一个SO问题修复它的尝试.

主要问题是:A)这是将PDF文件发送回浏览器的正确方法吗?B)如果不是,我如何更改代码以将pdf发送给浏览器?

理想情况下,我不想先将文件保存在服务器上,然后将其返回给控制器.我宁愿在保留所有内容的同时返回它.

最佳答案
final将始终被调用(即使在返回之后也是如此),因此它将始终在将内容流发送给客户端之前就将其丢弃,从而导致错误.

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"
        };
    }
}

无需额外的内存流

点击查看更多相关文章

转载注明原文:从ASP.NET Core 2控制器返回PDF - 乐贴网