ASP.NET MVC中的錯誤的錯誤處理跨越了兩個主要領域:程序異常和路由異常的處理。前者是關於在控制器和視圖中捕獲錯誤的;而后者更多是有關重定向和HTTP錯誤的。
1、在WebConfig中把過濾器配置啟動
<customErrors mode="On"> </customErrors>
控制器的代碼報錯時,會跳轉到~/Views/Shared/Error.cshtml頁面。mode="Off"頁面不會跳轉直接顯示錯誤信息。
2、綁定異常過濾器(過濾范圍是在controller的action方法中。)
public class FilterConfig { //效果相當於每個控制器的方法都添加了這個特性 //[HandleError(ExceptionType = typeof(NullReferenceException), View = "error")] //public ActionResult Index() public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } }
3、處理路由異常
<customErrors mode="On"> <error statusCode="404" redirect="~/Home/Index"/> </customErrors>
4、使用HTTP模塊的全局錯誤處理
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(); } }
