Ian*_*ink 10 c# asp.net asp.net-mvc asp.net-mvc-4
我在控制器上有一个简单的Action,它返回一个PDF.
工作良好.
public FileResult GetReport(string id)
{
byte[] fileBytes = _manager.GetReport(id);
string fileName = id+ ".pdf";
return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}
Run Code Online (Sandbox Code Playgroud)
当经理未能得到报告时,我会回来null或者是空的byte[].
当结果设置为?时,如何与浏览器通信存在问题FileResult?
Ada*_*lin 24
我会将您的方法的返回类型更改为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");
}
}
Run Code Online (Sandbox Code Playgroud)
将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);
}
Run Code Online (Sandbox Code Playgroud)
如果你想"与浏览器通信"有错误,标准的"HTTP方式"是返回状态代码500,特别是如果你的请求是使用Ajax调用的,这样你就可以优雅地处理异常.
我建议Exception在没有找到所提供的报告时简单地抛出id:
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");
}
Run Code Online (Sandbox Code Playgroud)
显式重定向到错误页面或返回a ViewResult不是ASP.NET MVC中的最佳方法,因为这通常是HandleError过滤器的角色(默认情况下应用),可以轻松配置为重定向或使用异常呈现某些View详细信息(同时仍保持HTTP状态500).
假设未能获取报告确实被视为异常,则这是真的.如果不是(例如,如果我们希望某些报告没有要转储的可用文件),则显式返回Redirect/View结果是完全可以接受的.
| 归档时间: |
|
| 查看次数: |
28342 次 |
| 最近记录: |