在ASP.NET MVC 5,我们可以捕捉错误的Global.asax.cs的Application_Error事件内部而不是每个查询使用try catch块。然后从重定向到自定义错误页面。
此外,我们还可以利用日志框架一样log4net的和NLOG。
例如,
protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
LogException(exception);
if (exception is HttpAntiForgeryException)
{
Response.Clear();
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
// Call target Controller and pass the routeData.
IController controller = EngineContext.Current.Locator.GetInstance<CommonController>();
var routeData = new RouteData();
routeData.Values.Add("controller", "Common");
routeData.Values.Add("action", "AntiForgery");
var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
controller.Execute(requestContext);
}
else
{
// Process 404 HTTP errors
var httpException = exception as HttpException;
if (httpException != null && httpException.GetHttpCode() == 404)
{
Response.Clear();
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
// Call target Controller and pass the routeData.
IController controller = EngineContext.Current.Locator.GetInstance<CommonController>();
var routeData = new RouteData();
routeData.Values.Add("controller", "Common");
routeData.Values.Add("action", "PageNotFound");
var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
controller.Execute(requestContext);
}
}
}
private void LogException(Exception ex)
{
if (ex == null)
return;
// Ignore 404 HTTP errors
var httpException = ex as HttpException;
if (httpException != null &&
httpException.GetHttpCode() == 404)
return;
try
{
// Log error message
}
catch (Exception)
{
// Don't throw new exception if occurs
}
}
您可以查看它们使用log4net的在GitHub样本项目。
来源
2017-07-13 19:14:53
Win
看看这篇文章https://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine#ExceptionhandlinginASP.NETMVC(6methodsexplained) – Nkosi
这也影响了我的答案在这里https://stackoverflow.com/questions/38247900/custom-error-pages-with-layout/38249656#38249656 – Nkosi