我对 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 问题让我相信我的怀疑是正确的。但即使在禁用全局后,HandleErrorAttribute
我仍然收到错误视图找不到错误!是什么赋予了?我唯一的另一个预感是我的基本控制器源自System.Web.Mvc.Controller
我试图检查源以查看是否HandleErrorAttribute
已应用System.Web.Mvc.Controller
但无法收集任何东西......
更新:我尝试覆盖我的基本控制器以将异常标记为这样处理:
protected override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
base.OnException(filterContext);
}
但这并没有解决问题。
UPDATE2:我在共享视图中放置了一个 Error.aspx 文件,只是为了看看会发生什么。当它在那里时,ELMAH 记录强制异常,然后提供共享视图 - 它永远不会达到Application_Error()
....不太确定该怎么做。