ASP.NET MVC错误处理的对应解决方法

2019-05-25 13:51:30王冬梅

可以设置全局过滤器,这样对每一个控制器都起作用。

App_Start文件夹下FilterConfig.cs文件中设置全局错误过滤器,过滤器会按照他们注册的顺序执行。但可以通过Order属性指定执行顺序。

例:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
      filters.Add(new HandleErrorAttribute 
      {
        ExceptionType = typeof(KeyNotFoundException),
        View = "KeyNotFound",
        Order = 2
      });
      filters.Add(new HandleErrorAttribute(),1);
    }
}

将自定义错误过滤器设置为全局过滤器:

在App_Start文件夹下FilterConfig.cs文件中

例:

public class FilterConfig
  {
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
      
       //其他过滤器

       filters.Add(new CustomHandleError());
     }
   }

2.2重写控制器OnException方法

注意将错误设置为已处理,不然错误继续抛出,但如果设置了全局错误过滤器,那么即使不标记为已处理,也不要紧,因为错误最终会被全局过滤器捕获并处理。

例:

public class HomeController : Controller
 {

    //其他控制器操作

    protected override void OnException(ExceptionContext filterContext)
    {
      if (filterContext==null)
        base.OnException(filterContext);

      //记录日志
      LogError(filterContext.Exception);

      //判断是否启用了自定义错误
      if (filterContext.HttpContext.IsCustomErrorEnabled)
      {
        //将错误设置为已处理
        filterContext.ExceptionHandled = true;
        //显示错误页
      this.View("Error").ExecuteResult(this.ControllerContext);
      }
    }
}

或者创建控制器基类

public class BaseController : Controller
  {
    protected override void OnException(ExceptionContext filterContext)
    {
      //错误日志记录
    }
  }

3全局错误处理

针对模型绑定或路由等过程中抛出的异常我们只能使用全局错误处理策略。

3.1 Global.asax中添加处理异常的代码

例:

 public class MvcApplication : System.Web.HttpApplication
  {
    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
      BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    protected void Application_Error(object sender, EventArgs e)
    {
      var exception = Server.GetLastError();
      if (exception == null)
      {
        return;
      }

      //异常发生记录日志或发送邮件

      //清除异常
      Server.ClearError();

      //重定向
      Response.Redirect("home/index");
    }
  }