我正在尝试进行简单的文件下载,但是会导致FileNotFoundException。
控制器中的代码:
public FileResult DownloadFile()
{
var fileName = "1.pdf";
var filePath = env.WebRootPath + "\\" + fileName;
var fileExists = System.IO.File.Exists(filePath);
return File(filePath, "application/pdf", fileName);
}
(调试变量fileExists显示它已设置为true。)
视图中的代码:
@Html.ActionLink("Download", "DownloadFile")
来自日志的消息:
2017-03-12 09:28:45 [INF] Executing action method "Team.Controllers.ModulesExController.DownloadFile (Team)" with arguments (null) - ModelState is Valid
2017-03-12 09:28:45 [DBG] Executed action method "Team.Controllers.ModulesExController.DownloadFile (Team)", returned result "Microsoft.AspNetCore.Mvc.VirtualFileResult".
2017-03-12 09:28:45 [INF] Executing FileResult, sending file as "1.pdf"
2017-03-12 09:28:45 [INF] Executed action "Team.Controllers.ModulesExController.DownloadFile (Team)" in 0.8238ms
2017-03-12 09:28:45 [DBG] System.IO.FileNotFoundException occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.
2017-03-12 09:28:45 [DBG] Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.
2017-03-12 09:28:45 [ERR] An unhandled exception has occurred while executing the request
System.IO.FileNotFoundException: Could not find file: D:\Projekti\Team\src\Team\wwwroot\1.pdf
如果我将链接粘贴到浏览器的错误消息中,我可以打开该文件。
答案 0 :(得分:9)
Controller.File()
期待虚拟路径,而不是绝对路径。
如果您想使用绝对路径,请传入一个流:
public FileResult DownloadFile()
{
var fileName = "1.pdf";
var filePath = env.WebRootPath + "\\" + fileName;
var fileExists = System.IO.File.Exists(filePath);
var fs = System.IO.File.OpenRead(filePath);
return File(fs, "application/pdf", fileName);
}
答案 1 :(得分:7)
在ASP.NET Core 2.0中,如果您有文件路径,则可以使用PhysicalFile作为返回类型。
public FileResult DownloadFile() {
var fileName = "1.pdf";
var filePath = env.WebRootPath + "\\" + fileName;
var fileExists = System.IO.File.Exists(filePath);
return PhysicalFile(filePath, "application/pdf", fileName);
}