[英]ASP.NET MVC 4 FileResult - In error
我在控制器上有一個簡單的Action,它返回一個PDF。
工作良好。
public FileResult GetReport(string id)
{
byte[] fileBytes = _manager.GetReport(id);
string fileName = id+ ".pdf";
return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}
當管理器無法獲得報告時,我得到null
或空byte[]
。
當結果設置為FileResult
時,如何與瀏覽器通信存在問題?
我會將您的方法的返回類型更改為ActionResult。
public ActionResult GetReport(string id)
{
byte[] fileBytes = _manager.GetReport(id);
if (fileBytes != null && fileBytes.Any()){
string fileName = id+ ".pdf";
return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}
else {
//do whatever you want here
return RedirectToAction("GetReportError");
}
}
FileResult
類繼承自ActionResult
。 因此,您可以像這樣定義您的Action:
public ActionResult GetReport(string id)
{
byte[] fileBytes = _manager.GetReport(id);
string fileName = id + ".pdf";
if(fileBytes == null || fileBytes.Length == 0)
return View("Error");
return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}
如果你想“與瀏覽器通信”有錯誤,標准的“HTTP方式”是返回狀態代碼500,特別是如果你的請求是使用Ajax調用的,這樣你就可以優雅地處理異常。
我建議在找不到提供的id
報告時簡單地拋出Exception
:
public FileResult GetReport(string id)
{
// could internally throw the Exception inside 'GetReport' method
byte[] fileBytes = _manager.GetReport(id);
// or...
if (fileBytes == null || !fileBytes.Any())
throw new Exception(String.Format("No report found with id {0}", id));
return File(fileBytes, MediaTypeNames.Application.Octet, fileName = id+ ".pdf");
}
顯式重定向到錯誤頁面或返回ViewResult
不是ASP.NET MVC中的最佳方法,因為這通常是HandleError
過濾器(默認情況下應用)的角色,可以輕松配置為重定向或呈現某些View異常詳細信息(同時仍保持HTTP狀態500)。
假設未能獲取報告確實被視為異常,則這是真的。 如果不是(例如,如果我們希望某些報告沒有要轉儲的可用文件),則顯式返回Redirect/View
結果是完全可以接受的。
處理先決條件的另一種解決方法是將下載過程分為兩個階段。 首先是檢查服務器端方法中的前提條件,該方法作為ajax / post方法執行。
然后,如果滿足這些前提條件,您可以開始下載請求(例如,在onSuccess回調中檢查指示履行的返回值),其中(在服務器端)您將以上述帖子中描述的方式處理潛在的異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.