Asp.net mvc 2 如何处理asp.net mvc错误并从控制器使用相同的视图?
我有这样的行为:Asp.net mvc 2 如何处理asp.net mvc错误并从控制器使用相同的视图?,asp.net-mvc-2,error-handling,tempdata,Asp.net Mvc 2,Error Handling,Tempdata,我有这样的行为: [AcceptVerbs(HttpVerbs.Post)] public ActionResult New(Product product) { try { if(ModelState.IsValid) { _productService.Create(product); TempData["success"] = "Product created successfully!";
[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]操作方式不同,它不会在出现错误时将用户重定向到另一个视图,而是返回带有TempData[error]的同一视图,并在同一页面的顶部显示通知
我如何才能做到这一点,删除所有这些try{}catch{}代码,并将此逻辑置于此操作之外,以及其他操作?您应该能够使用[HandleError]和OneException来执行您想要的操作。例如,要显示自定义视图:
protected override void OnException(ExceptionContext filterContext)
{
// Output a nice error page
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
this.View("Error").ExecuteResult(this.ControllerContext);
}
}
不久前,我在我的博客上发布了更多关于这方面的信息: