如何重定向到MVC FileDownloadResult中的特定错误页面

时间:2015-11-12 03:43:32

标签: c# asp.net-mvc-3

我允许我的用户下载文件,有时文件存档或不存在的位置,我目前显示404,我为这个特定场景创建了一个特定的错误页面,但我无法显示它,因为我必须在FileDownload结果中返回一些内容,我无法进行响应重定向。此外,我尝试使用javascript返回内容,但这也与FileDownloadResult类型不兼容。如何将用户路由到我将从其自己的控制器/操作呈现的预期错误页面?

   public DownloadFileResult Download(string file)
        {
            try
            {
                string loadLististFileName = file;

                // get the displayed filename, extract the file name
                string fileNamePath = loadLististFileName;
                string fileName = Path.GetFileName(fileNamePath);
                string dirName = Path.GetDirectoryName(fileNamePath);

                string dirPath = dirName.Replace("\\", ",");

                string[] dir = dirPath.Split(',');
                int dirlength = dir.Length;
                string year = dir[dirlength - 3];
                string month = dir[dirlength - 2];
                string day = dir[dirlength - 1];

                var fileData = IOHelper.GetFileData(fileName, dirName);

                fileName = IOHelper.GetPrimaryFileName(file);

                return new DownloadFileResult(fileName, fileData);
            }
            catch (FileNotFoundException)
            {

                //return Content("<script language='javascript' type='text/javascript'>alert('Image not found!');</script>");            

                Response.Redirect("Exception/FileIndex");
            }

        }

1 个答案:

答案 0 :(得分:0)

尝试返回ActionResult,如下所示:

    public ActionResult DownLoadFile(int Id)
    {
        var model = new PreviewFileAttachmentViewModel(Id, _attachFileProvider);
        if (model.FileExist)
            return File(model.AbsFileNamePath, model.ContentType, model.FileName);
        else
            return RedirectToAction("FileNotFound");
    }