小编New*_*MVC的帖子

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

我有一个目录“下载”,我有我们的客户可以下载的静态文件。我正在使用以下 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 …

c# asp.net-mvc asp.net-mvc-5 asp.net-mvc-5.1 asp.net-mvc-5.2

2
推荐指数
1
解决办法
6505
查看次数