Mer*_*n04 3 c# asp.net-core-mvc system.io.file
我正在尝试从 ASP.NET Core 中的操作返回文件:
public IActionResult GetFile(string filePath) {
return File("/home/me/file.png", "application/octet-stream");
}
Run Code Online (Sandbox Code Playgroud)
但是,我得到了
System.IO.FileNotFoundException
在我的浏览器窗口中:
处理请求时发生未处理的异常。FileNotFoundException:找不到文件:/home/me/file.png
Microsoft.AspNetCore.Mvc.Infrastruct.VirtualFileResultExecutor.ExecuteAsync(ActionContext上下文,VirtualFileResult结果)
我尝试使用检查文件是否存在System.IO.File.Exists并在中查找它Directory.GetFiles,两者都表示文件确实存在。我也尝试过将媒体类型更改为image/png,但这没有任何帮助。
为什么我会收到此错误,如何修复它?
这是我在应用程序中使用的,它工作得很好:
[HttpGet]
[Route("download")]
public async Task<iactionresult> Download([FromQuery] string file) {
var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, file);
if (!System.IO.File.Exists(filePath))
return NotFound();
var memory = new MemoryStream();
using (var stream = new FileStream(filePath, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(filePath), file);
}
Run Code Online (Sandbox Code Playgroud)
这个片段来自这里:我的代码略有不同。