Chr*_*mes 7 model-view-controller asp.net-mvc asp.net-mvc-3
我有一个返回void的控制器方法,因为它正在构建一个Excel报告供用户下载.我们正在使用的Excel第三方库正在写入响应本身.该方法看起来像这样:
[HttpGet]
public void GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
excelReport.DownloadReport(System.Web.HttpContext.Current.Response);
}
catch (Exception ex)
{
// This is wrong, of course, because I'm not returning an ActionResult
Response.RedirectToRoute("/Report/Error/", new { exceptionType = ex.GetType().Name });
}
}
Run Code Online (Sandbox Code Playgroud)
如果用户未获得用于获取报告的特定凭据,则会进行多项安全检查以引发异常.我想重定向到另一个页面并传递有关异常的一些信息,但我无法弄清楚如何在MVC3中执行此操作....
有任何想法吗?
你可以做一个
Response.Redirect(Url.Action("Error", "Report", new { exceptionType = ex.GetType().Name });
Run Code Online (Sandbox Code Playgroud)
但是你看过FilePathResult还是FileStreamResult?
不要让第三部分库直接写入响应来获取内容,而是使用常规方法ActionResult并返回File(...)实际文件或RedirectToAction(...)(或RedirectToRoute(...))错误。如果您的第 3 方库只能写入 Response,您可能需要使用一些技巧来捕获其输出。
[HttpGet]
public ActionResult GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
var content = excelReport.MakeReport(System.Web.HttpContext.Current.Response);
return File(content, "application/xls", "something.xls");
}
catch (Exception ex)
{
RedirectToRoute("/Report/Error/", new { exceptionType = ex.GetType().Name });
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9740 次 |
| 最近记录: |