【发布时间】:2013-05-18 00:19:01
【问题描述】:
我对 Global.asax 进行了一些修改,以便可以显示自定义错误页面(403、404 和 500)这是代码:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
//FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_Error(object sender, EventArgs e)
{
if (Context.IsCustomErrorEnabled)
{
ShowCustomErrorPage(Server.GetLastError());
}
}
private void ShowCustomErrorPage(Exception exception)
{
HttpException httpException = exception as HttpException;
if (httpException == null)
{
httpException = new HttpException(500, "Internal Server Error", exception);
}
Response.Clear();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("fromAppErrorEvent", true);
switch (httpException.GetHttpCode())
{
case 403:
routeData.Values.Add("action", "AccessDenied");
break;
case 404:
routeData.Values.Add("action", "NotFound");
break;
case 500:
routeData.Values.Add("action", "ServerError");
break;
default:
routeData.Values.Add("action", "DefaultError");
routeData.Values.Add("httpStatusCode", httpException.GetHttpCode());
break;
}
Server.ClearError();
IController controller = new ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
}
我还在我的 Web.Config 中添加了以下内容:
<customErrors mode="On">
<!-- There is custom handling of errors in Global.asax -->
</customErrors>
自定义错误页面正确显示,ELMAH 将正确记录(故意)抛出的错误。但是 ELMAH 也会捕获并记录一个额外的错误:
System.InvalidOperationException: The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/account/Error.aspx ~/Views/account/Error.ascx ~/Views/Shared/Error.aspx ~/Views/Shared/Error.ascx ~/Views/account/Error.cshtml ~/Views/account/Error.vbhtml ~/Views/Shared/Error.cshtml ~/Views/Shared/Error.vbhtml
我的第一直觉让我在过滤器配置中禁用了全局HandleErrorAttribute。而且,类似的 SO 问题,例如:MVC problem with custom error pages 让我相信我的怀疑是正确的。但即使在禁用全局HandleErrorAttribute 之后,我仍然收到无法找到错误视图的错误!是什么赋予了?我唯一的另一个预感是我的基本控制器源自System.Web.Mvc.Controller 我试图检查源代码以查看HandleErrorAttribute 是否应用于System.Web.Mvc.Controller 但无法收集任何东西...
更新: 我尝试覆盖我的基本控制器以将异常标记为这样处理:
protected override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
base.OnException(filterContext);
}
但这并没有解决问题。
更新2:
我在共享视图中放置了一个 Error.aspx 文件,只是为了看看会发生什么。当它在那里时,ELMAH 记录强制异常,然后提供共享视图 - 它永远不会到达 Application_Error() .... 不太清楚该怎么做。
【问题讨论】:
标签: c# asp.net-mvc-4 elmah