我有这样的 Action :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult New(Product product)
{
try
{
if(ModelState.IsValid)
{
_productService.Create(product);
TempData["success"] = "Product created successfully!";
return RedirectToAction("Edit", new { product.Id });
}
}
catch (Exception e)
{
Logger.Exception(e);
TempData["error"] = "Oops, an error occurred! Please try again in a few moments.";
}
return View(product);
}
我想从方法中排除这种错误处理逻辑。但是,代替默认的[HandleError]处理方式,而不是在发生错误的情况下将用户重定向到另一个 View ,它会以TempData [“error”]返回给我相同的 View ,并且通知将显示在在同一页面的顶部。
我该怎么做,删除所有try {} catch {}代码,并将此逻辑放在该操作之外,以及其他操作?
最佳答案
您应该可以使用[HandleError]和OnException做您想要的事情。例如,显示自定义 View :
protected override void OnException(ExceptionContext filterContext)
{
// Output a nice error page
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
this.View("Error").ExecuteResult(this.ControllerContext);
}
}
我不久前在我的博客上发布了一些有关此信息:
http://blog.dantup.com/2009/04/aspnet-mvc-handleerror-attribute-custom.html
关于asp.net-mvc-2 - 如何处理asp.net mvc错误并使用 Controller 中的同一 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4269589/