在mvc中使用Action Result作为返回类型时,return文件不存在

return file not exist when use Action Result as returen type in mvc

本文关键字:返回类型 return 不存在 文件 mvc Result Action      更新时间:2023-09-26

我有一个动作链接

    @Html.ActionLink(@Resources.Resource_ar.Download, "DownloadFile", new { Communicationid = item.Communicationid }, new { @class = "btn btn-success btn_Download" })

调用动作下载文件

   public ActionResult DownloadFile(string Communicationid)
    {

        string pathString = Settings.getSettingValue("FolderForSaveCommunicationsAttachments");
        //string FullPath = Path.Combine(Server.MapPath("~/Content/UploadedAttachment/"), FileName);
        string FullPath = Path.Combine(pathString, Communicationid);

        Communications ObjCommunication = new Communications(int.Parse(Communicationid));
        string FileName = ObjCommunication.s_FileName;
        //return File(FullPath, "text/docx");
        if (System.IO.File.Exists(FullPath))
        {
            string contentType = string.Empty;
            if (FileName.Contains(".pdf"))
            {
                contentType = "application/pdf";
            }
            else if (FileName.Contains(".docx"))
            {
                contentType = "application/docx";
            }
            else if (FileName.Contains(".doc"))
            {
                contentType = "application/doc";
            }
            else if (FileName.Contains(".jpeg"))
            {
                contentType = "image/jpeg";
            }
            else if (FileName.Contains(".jpg"))
            {
                contentType = "image/jpg";
            }
            else if (FileName.Contains(".png"))
            {
                contentType = "image/png";
            }
            else if (FileName.Contains(".bmp"))
            {
                contentType = "image/bmp";
            }
            else if (FileName.Contains(".xlsx"))
            {
                contentType = "application/xlsx";
            }
            else if (FileName.Contains(".Exl"))
            {
                contentType = "application/Exl";
            }
            else if (FileName.Contains(".txt"))
            {
                contentType = "application/txt";
            }
            return File(FullPath, contentType, FileName);
        }
        else
        {
            return;
        }
    }

问题是,当文件存在时,它返回文件并正确下载它,但当文件不存在时,我想向用户显示警告,告诉他文件不存在,我应该返回什么我试着返回javascript("alert('file not exist')"),把它给了我空白页的文本,我把"alert('file not exist')"对这个问题有什么帮助吗提前感谢

你可以这样做:

 if (System.IO.File.Exists(FullPath))
                { //....
                }
                else { return Content("Some error message"); }

但我宁愿返回404,如果该文件不存在。