ASP.NET MVC中异常处理&自定义错误页详析

2019-05-25 13:18:21于海丽

注册HandleErrorAttribute(使用默认的错误视图页面文件名)

public class FilterConfig
 {
  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  {
   filters.Add(new HandleErrorAttribute());
  }
 }

定义Error.cshtml视图页

@{
 Layout = null;
}
@model HandleErrorInfo
<!DOCTYPE html>
<html>
<head>
 <meta name="viewport" content="width=device-width" />
 <title>Error</title>
</head>
<body>
 <div>
  @*通过HandleErrorAttribute异常过滤器捕获到的异常信息存储在Model属性中*@
  @Model.Exception.Message
 </div>
</body>
</html>

之所以通过注册HandleErrorAttribute过滤器捕获的异常在错误页中能获取异常信息可以看HandleErrorAttribute类的内部实现,发现加载错误视图页面的过程中,传递了一个HandleErrorInfo对象过去。

public virtual void OnException(ExceptionContext filterContext)
{
 if (filterContext == null)
 {
  throw new ArgumentNullException("filterContext");
 }
 if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
 {
  Exception innerException = filterContext.Exception;
  if ((new HttpException(null, innerException).GetHttpCode() == 500) && this.ExceptionType.IsInstanceOfType(innerException))
  {
   string controllerName = (string) filterContext.RouteData.Values["controller"];
   string actionName = (string) filterContext.RouteData.Values["action"];
   HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
   ViewResult result = new ViewResult {
    ViewName = this.View,
    MasterName = this.Master,
    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
    TempData = filterContext.Controller.TempData
   };
   filterContext.Result = result;
   filterContext.ExceptionHandled = true;
   filterContext.HttpContext.Response.Clear();
   filterContext.HttpContext.Response.StatusCode = 500;
   filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
  }
 }
}
public string View
{
 get
 {
  if (string.IsNullOrEmpty(this._view))
  {
   return "Error";
  }
  return this._view;
 }
 set => 
  (this._view = value);
}

三、总结

总的来说,Application_Error方法用于处理针对请求管道级别的发生的异常错误,而Mvc异常过滤器则只能处理在执行action方法过程中出现的异常.能处理的范围相对Application_Error较小,但在实际项目开发中,用Mvc异常过滤器处理异常相对会多一点,因为我们的功能业务往往体现在控制器的action方法执行的过程中,也就是在这个过程中较容易产生异常。故开发中用Mvc异常过滤器就能适应大部分的异常处理需求。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。