asp net core - 文件下载结果为 FileNotFoundException
Posted
技术标签:
【中文标题】asp net core - 文件下载结果为 FileNotFoundException【英文标题】:asp net core - file download results is FileNotFoundException 【发布时间】:2017-08-02 09:38:33 【问题描述】:我正在尝试进行简单的文件下载,但结果是 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
如果我将链接粘贴到浏览器的错误消息中,我可以打开文件。
【问题讨论】:
我的回答解决了你的问题吗? 【参考方案1】:在 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);
【讨论】:
你的答案和前面的答案有什么实际区别? 1.更少的代码(少一行)。 2. 不打开你没有关闭的流。 3. 更简洁的代码,这可能是他们在 Core 2 中添加它的原因。 另外,如果您使用流,我不确定兑现标头是否设置正确。【参考方案2】:Controller.File()
期待 虚拟路径,而不是绝对路径。
见https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.mvc.controllerbase#Microsoft_AspNetCore_Mvc_ControllerBase_File_System_String_System_String_System_String_
如果要使用绝对路径,传入一个流:
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);
【讨论】:
链接已断开以上是关于asp net core - 文件下载结果为 FileNotFoundException的主要内容,如果未能解决你的问题,请参考以下文章
如何将 ASP.NET Core 5 Web API 控制器操作的失败模型验证结果包装到另一个类中并将响应返回为 OK