alo*_*ida 3 c# exception-handling asp.net-mvc-3
我使用下面的代码实现了异常处理.[编辑开始]我不知道它为什么两次调用视图.[已编辑完成]
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);
}
}
Run Code Online (Sandbox Code Playgroud)
HomeController的
public class HomeController : BaseController
{
public ActionResult Exception2()
{
throw (new ArgumentOutOfRangeException());
}
public ActionResult Exception3()
{
throw (new Exception());
}
}
Run Code Online (Sandbox Code Playgroud)
错误视图(仅限共享文件夹)
@model System.Web.Mvc.HandleErrorInfo
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h2>
Sorry, an error occurred while processing your request.
</h2>
<h3>
@if (Model != null)
{
<p>@Model.Exception.GetType().Name<br />
thrown in @Model.ControllerName @Model.ActionName</p>
<br />
@Model.Exception
}
</h3>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
OutOfRange视图(仅限共享文件夹)
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>OutOfRange Exception</title>
</head>
<body>
<div>
<h3>
@if (Model != null)
{
<p>@Model.Exception.GetType().Name<br />
thrown in @Model.ControllerName @Model.ActionName</p>
<br />
@Model.Exception
}
</h3>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
执行网址: http://[domainName]/Home/Exception2
这里工作正常.[编辑:这里也打了两次电话.]

执行网址: http://[domainName]/Home/Exception3
这里工作不正常.您可以看到"抱歉,处理您的请求时出错".来了两次.当我使用上面的URL调试应用程序时,错误视图调用两次(第一次模型为空,第二次模型包含一些值).我可以知道我的实施有什么问题吗?

要尝试的事情:
HandleError从您的默认全局操作过滤器属性中删除Global.asax它.当您创建新的ASP.NET MVC 3应用程序时,默认模板会在RegisterGlobalFilters方法中注册它.因此注释掉注册此属性的行.在web.config中启用自定义错误:
<customErrors mode="On" />
Run Code Online (Sandbox Code Playgroud)更新:
如果要将模型传递给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<HandleErrorInfo>(model)
};
filterContext.Result = result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3437 次 |
| 最近记录: |