Mar*_*rko 9 asp.net-mvc download
我正在尝试进行简单的文件下载,但它会导致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);
}
Run Code Online (Sandbox Code Playgroud)
(调试变量fileExists表明它已设置为true.)
视图中的代码:
@Html.ActionLink("Download", "DownloadFile")
Run Code Online (Sandbox Code Playgroud)
来自日志的消息:
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
Run Code Online (Sandbox Code Playgroud)
如果我在浏览器中的错误消息中粘贴链接,我可以打开该文件.
chr*_*ofr 10
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);
}
Run Code Online (Sandbox Code Playgroud)
在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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3772 次 |
| 最近记录: |