2015-11-12 110 views
0

我讓我的用戶下載文件,有時文件被存檔或在該位置不存在,我目前顯示404,我創建了一個特定的錯誤頁面對於該特定場景但我無法顯示它,因爲我必須在FileDownload Result中返回一些內容,並且我無法做出響應重定向。此外,我試圖用JavaScript返回內容,但這也與FileDownloadResult類型不兼容。如何將用戶路由到預定的錯誤頁面,我將從其自己的控制器/操作中呈現?如何重定向到特定的錯誤頁面在MVC 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"); 
      } 

     } 

回答

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"); 
    } 
+0

他還是應該把它包在一個try/catch塊,以防萬一,但。 – IyaTaisho

相關問題