Ant*_*ttu 3 c# download asp.net-core
我在控制器方法中有此代码;
try
{
return PhysicalFile("c:\temp\my-non-existing-file.txt", "text/plain");
}
catch (FileNotFoundException)
{
return NotFound();
}
Run Code Online (Sandbox Code Playgroud)
但是,在这种情况下不运行 catch 子句,而是将 a500 Internal Server Error返回给浏览器。使开发人员错误页面处于活动状态,表明FileNotFoundException确实抛出了 a ,但调用堆栈显示它来自中间件。
try
{
return PhysicalFile("c:\temp\my-non-existing-file.txt", "text/plain");
}
catch (FileNotFoundException)
{
return NotFound();
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释如何正确处理这种情况并返回404 Not Found吗?
更新:添加了完整堆栈(带有一些名称清理)
正如@KirkLarkin 正确指出的那样,文件直到稍后才会解析,当响应被假脱机时,这发生在您的操作已经退出之后。因此,您无法在此处捕获该异常。您可能可以使用自定义中间件或异常处理程序来做一些事情,但老实说,为什么不直接执行以下操作:
var filename = "c:\temp\my-non-existing-file.txt";
if (File.Exists(filename))
{
return PhysicalFile(filename, "text/plain");
}
else
{
return NotFound();
}
Run Code Online (Sandbox Code Playgroud)
主动检查条件总是更好,而不是依靠捕获异常。过度依赖异常处理会降低您的应用程序性能。