为什么ASP.NET MVC 3exception被“处理”两次?
我已经使用下面的代码实现了exception处理。[编辑开始]我不知道它为什么两次调用视图。 [已编辑完成]
Basecontroller
public class BaseController : Controller { protected override void OnException(ExceptionContext filterContext) { if (filterContext.HttpContext.IsCustomErrorEnabled) { filterContext.ExceptionHandled = true; if (filterContext.Exception.GetType() == typeof(ArgumentOutOfRangeException)) { this.View("OutOfRange").ExecuteResult(this.ControllerContext); } else { this.View("Error").ExecuteResult(this.ControllerContext); } } base.OnException(filterContext); } }
HomeController的
public class HomeController : BaseController { public ActionResult Exception2() { throw (new ArgumentOutOfRangeException()); } public ActionResult Exception3() { throw (new Exception()); } }
错误视图(仅限共享文件夹)
@model System.Web.Mvc.HandleErrorInfo @{ Layout = null; } Error Sorry, an error occurred while processing your request.
@if (Model != null) {
@Model.Exception.GetType().Name
thrown in @Model.ControllerName @Model.ActionName
@Model.Exception }
OutOfRange视图(仅限共享文件夹)
@{ Layout = null; } OutOfRange Exception @if (Model != null) {
@Model.Exception.GetType().Name
thrown in @Model.ControllerName @Model.ActionName
@Model.Exception }
执行URL: http://[domainName]/Home/Exception2
这里工作正常。 [编辑:这里也叫两次。]
执行URL: http://[domainName]/Home/Exception3
这里工作不正常。 您可以看到“抱歉,处理您的请求时出错”。 来了两次。 当我使用上面的URL调试应用程序时,错误视图调用两次(第一次模型为空,第二次模型包含一些值)。 我可以知道我的实施有什么问题吗?
要尝试的事情:
- 从
Global.asax
删除默认的HandleError
全局操作filter属性(如果存在)。 创建新的ASP.NET MVC 3应用程序时,默认模板会在RegisterGlobalFilters
方法中注册它。 因此注释掉注册此属性的行。 -
在web.config中启用自定义错误:
更新:
如果要将模型传递给Error.cshtml
视图(因为它强烈键入HandleErrorInfo
),您可以执行以下操作:
else { string controllerName = filterContext.RouteData.GetRequiredString("controller"); string actionName = filterContext.RouteData.GetRequiredString("action"); var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); var result = new ViewResult { ViewName = "Error", ViewData = new ViewDataDictionary(model) }; filterContext.Result = result; }
添加base.OnException(filterContext);
在if (filterContext.HttpContext.IsCustomErrorEnabled)
之前if (filterContext.HttpContext.IsCustomErrorEnabled)
protected override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); if (filterContext.HttpContext.IsCustomErrorEnabled) }
我有同样的问题,但我设法通过添加以下内容来解决错误:
Response.End();
到我的OnException方法结束。
我知道这不是理想的解决方案,但是,它确实至少让我脱离了约束,直到我可以调查更完整的选项。