PDF 强制下载而不是在浏览器中打开

3

我正在使用RazorPDF,希望将PDF强制下载而不是在浏览器标签页中打开。如何实现?谢谢。

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string Id)
{
    return RedirectToAction("Pdf");
}

public PdfResult Pdf()
{
    // With no Model and default view name.  Pdf is always the default view name
    return new PdfResult();
}

你需要在响应头中设置 content-disposition - 参考 https://dev59.com/ZnNA5IYBdhLWcg3wUMDn。 - adrianbanks
在上面的代码中,我该如何做到这一点? - dotnet-practitioner
我没有使用过RazorPDF,但是你可以在返回PDF文件之前,在你的操作中添加链接答案中的代码来完成它。 - adrianbanks
2个回答

8
尝试在返回 PDFResult 对象之前添加 content-disposition 标头。
public PdfResult Pdf()
{
  Response.AddHeader("content-disposition", "attachment; filename=YourSanitazedFileName.pdf");

  // With no Model and default view name.  Pdf is always the default view name
  return new PdfResult();
}

IronGeek,我没有任何.pdf文件可以返回。所以我不确定你的代码是否适用于我的情况。谢谢。 - dotnet-practitioner
@dotnet-practitioner,你不必使用特定的名称,可以使用任何名称。你甚至可以为其使用随机名称。浏览器将使用该名称作为下载文件对话框中的文件名。 - IronGeek

0
你应该查看“Content-Disposition”头;例如将“Content-Disposition”设置为“attachment; filename=FileName.pdf”将提示用户(通常)出现“另存为:FileName.pdf”对话框,而不是打开它。然而,这需要来自正在下载的请求,因此您无法在重定向期间执行此操作。但是,ASP.NET提供了Response.TransmitFile以实现此目的。例如(假设您没有使用MVC,它具有其他首选选项):
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=FileName.pdf");
Response.TransmitFile(filePath);
Response.End(); 

如果您正在尝试打开API中的文件,则需要将流转换为字节数组,然后填充内容。
            HttpResponseMessage result = null;
            result = Request.CreateResponse(HttpStatusCode.OK);
            FileStream stream = File.OpenRead(path);
            byte[] fileBytes = new byte[stream.Length];
            stream.Read(fileBytes, 0, fileBytes.Length);
            stream.Close();           
            result.Content = new ByteArrayContent(fileBytes);
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "FileName.pdf";            

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接