ASP.NET MVC 文件内容结果内联 PDF 文件名未显示在浏览器标题中



.NET Framework 4.7.2 MVC 项目

我有一个控制器操作,可以动态加载 PDF 以内联返回到浏览器。一切正常,除了文件名未显示在浏览器标题栏或选项卡中。相反,浏览器显示"id"参数的值,大概是因为它跟在最后一个斜杠后面。

我需要浏览器显示 PDF 文件名,以便用户知道他们正在查看的 PDF。我们的用户倾向于在选项卡中打开多个 PDF 并经常在它们之间切换。这是代码的简化版本:

public FileContentResult ViewPDF(int id)
{
byte[] pdfContents = loadPDF(id);
string filename = getPDFFilename(id);
var cd = new ContentDisposition
{
FileName = filename,
Inline = true
};
Response.AddHeader("Content-Disposition", cd.ToString());
string returnContentType = MimeMapping.GetMimeMapping(filename);            
return File(pdfContents, returnContentType);
}

我也尝试过FileStream,但没有运气,并尝试过Edge,IE和Chrome,但它们都做同样的事情。在Chrome中,当我保存PDF时,它确实使用正确的文件名保存,但不会在浏览器中显示它。

这不是理想的解决方案,但我最终创建了一个新的视图页面,其中包含一个全屏<iframe>,用于内联加载PDF。这样,我至少可以在页面标题中显示PDF名称,该标题显示在选项卡中。

类似这个:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewData["Title"]</title>
<style type="text/css">
body, html {
width: 100%;
height: 100%;
overflow: hidden;
margin: 0;
}
.pdfFrame {
width: 100%;
height: 100%;
border: none;
}
</style>
</head>
<body class="nomargins">
<iframe class="pdfFrame" src="@Url.Action("GetPDF", new { id = ViewBag.pdfID })" frameBorder="0"></iframe>
</body>
</html>

最新更新