你已經顯示的代碼表示,供應從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