我在 MVC (4) 中设置了错误处理,效果很好。我已经在 global.asax 中注册了 HandleErrorAttribute 并在 web.config 中设置了适当的配置。但是,如果我重定向到错误视图并且错误视图本身引发错误,我将被重定向回错误页面 - 无休止。错误发生在布局和应用程序外部管理的布局中。如果布局中有错误,我会感到很沮丧。我怎样才能防止这种情况?我应该使用哪种错误处理回退?使用不同的布局不是一种选择。
问问题
521 次
1 回答
1
这是我的做法。试试看:
protected void Application_Error(object sender, EventArgs e)
{
//Retrieving the last server error
var exception = Server.GetLastError();
//Erases any buffered HTML output
Response.Clear();
//Declare the exception
var httpException = exception as HttpException;
var routeData = new RouteData();
routeData.Values.Add("controller", "Error"); //Adding a reference to the error controller
if (httpException == null)
{
routeData.Values.Add("action", "ServerError"); //Non HTTP related error handling
}
else //It's an Http Exception, Let's handle it.
{
switch (httpException.GetHttpCode())
{
//these are special views to handle each error
case 401:
case 403:
//Forbidden page.
routeData.Values.Add("action", "Forbidden");
break;
case 404:
//Page not found.
routeData.Values.Add("action", "NotFound");
break;
case 500:
routeData.Values.Add("action", "ServerError");
break;
default:
routeData.Values.Add("action", "Index");
break;
}
}
//Pass exception details to the target error View.
routeData.Values.Add("message", exception);
//Clear the error on server.
Server.ClearError();
//Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
// Call target Controller and pass the routeData.
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(
new HttpContextWrapper(Context), routeData));
}
于 2013-02-27T19:36:00.180 回答