使用 FileStreamResult 找不到下载文件时返回消息

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 错误页面的页面。

nik*_*ale 5

我建议将您的返回类型设置为基于 ActionResult 而不是 FileStreamResult ,然后您可以灵活地处理这个问题。

  1. 您可以重定向到您的自定义方法,然后您可以从中提供正确的消息/视图。
  2. 通过异常和配置文件句柄 404 与您的自定义错误文件。(抛出新的 HttpException(404, "未找到");)

希望这能解决您的问题。