New*_*MVC 2 c# asp.net-mvc asp.net-mvc-5 asp.net-mvc-5.1 asp.net-mvc-5.2
我有一个目录“下载”,我有我们的客户可以下载的静态文件。我正在使用以下 ActionLink 来调用文件:
@Html.ActionLink("Download Example", "Download", new { area = "", controller = "Common", fileName = "SomeFile.xlsx" })
Run Code Online (Sandbox Code Playgroud)
调用“Common”控制器并使用以下代码返回文件:
public FileStreamResult Download(string fileName)
{
var filePath = Server.MapPath("~/Download/" + fileName);
var ext = Path.GetExtension(fileName);
switch (ext)
{
case ".xlsx":
return new FileStreamResult(new FileStream(filePath, FileMode.Open),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
case ".xls":
return
new FileStreamResult(
new FileStream(Server.MapPath("~/Download/" + fileName), FileMode.Open),
"application/vnd.ms-excel");
case ".pdf":
return
new FileStreamResult(
new FileStream(Server.MapPath("~/Download/" + fileName), FileMode.Open),
"application/pdf");
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,由于我没有返回视图,如何向视图返回消息以显示文件是否不存在(404)?
我已经想通了这么多:
if (!System.IO.File.Exists(filePath))
{
}
Run Code Online (Sandbox Code Playgroud)
但我不知道该返回什么以避免 404 重定向。我想在页面内返回一条消息“找不到文件”或类似的内容,而不是重定向到 404 错误页面的页面。
我建议将您的返回类型设置为基于 ActionResult 而不是 FileStreamResult ,然后您可以灵活地处理这个问题。
希望这能解决您的问题。
| 归档时间: |
|
| 查看次数: |
6505 次 |
| 最近记录: |