你已经显示的代码表示,供应从App_Code
文件夹中的文件的控制器操作。从硬盘上的任意位置提供文件将是一个巨大的安全漏洞。所以我建议你坚持这种做法。但是这个代码仍然存在缺陷。恶意用户仍然可以使用特制的url在硬盘上显示任意文件。这可以被固定了以下行动:
public ActionResult GetFile(string file)
{
var appData = Server.MapPath("~/App_Data");
var path = Path.Combine(appData, file);
path = Path.GetFullPath(path);
if (!path.StartsWith(appData))
{
// Ensure that we are serving file only inside the App_Data folder
// and block requests outside like "../web.config"
throw new HttpException(403, "Forbidden");
}
if (!System.IO.File.Exists(path))
{
return HttpNotFound();
}
return File(path, MediaTypeNames.Application.Pdf);
}
,现在你可以使用embed
标签链接到这个控制器动作:
<object data="@Url.Action("GetFile", "SomeController", new { file = "test.pdf" })" type="application/pdf" width="300" height="200">
alt : @Html.ActionLink("test.pdf", "SomeController", "Home", new { file = "test.pdf" })
</object>
或iframe
如果你喜欢:
<iframe src="@Url.Action("GetFile", "SomeController", new { file = "foo.pdf" })" style="width:718px; height:700px;" frameborder="0"></iframe>
文件已下载。我需要在我的“视图”中显示该pdf。 – Krishan
下载到哪里?怎么样 ? – Shyju