2017-03-12 89 views
2

我試圖做一個簡單的文件下載,但它與FileNotFoundException的結果。asp net core - 文件下載結果是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表明,它被設置爲真。)

視圖中的代碼:從所述

@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

我的答案是否解決了您的問題? – christofr

回答

3

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); 
} 
0

在ASP.NET 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

你和前面的答案有什麼實際區別? – Marko

+1

1.較少的代碼(少一行)。 2.不要打開你沒有關閉的流。 3.一些簡潔的代碼可能是爲什麼他們將其添加到Core 2中。 –