ASP.NET MVC異常過濾器用法
我們平常在程序里面為了捕獲異常,會加上try-catch-finally代碼,但是這樣會使得程序代碼看起來很龐大,在MVC中我們可以使用異常過濾器來捕獲程序中的異常,如下圖所示:
使用了異常過濾器以后,我們就不需要在Action方法里面寫Try -Catch-Finally這樣的異常處理代碼了,而把這份工作交給HandleError去做,這個特性同樣可以應用到Controller上面,也可以應用到Action方面上面。
注意:
使用異常過濾器的時候,customErrors配置節(jié)屬性mode的值,必須為On。
演示示例:
1、Error控制器代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using System.IO; namespace _3_異常過濾器.Controllers { public class ErrorController : Controller { // GET: Error [HandleError(ExceptionType =typeof(ArithmeticException),View ="Error")] public ActionResult Index(int a,int b) { int c = a / b; ViewData["Result"] = c; return View(); } /// <summary> /// 測試數據庫異常 /// </summary> /// <returns></returns> [HandleError(ExceptionType = typeof(SqlException), View = "Error")] public ActionResult DbError() { // 錯誤的連接字符串 SqlConnection conn = new SqlConnection(@"Initial Catalog=StudentSystem; Integrated Security=False;User Id=sa;Password=******;Data Source=127.0.0.1"); conn.Open(); // 返回Index視圖 return View("Index"); } /// <summary> /// IO異常 /// </summary> /// <returns></returns> [HandleError(ExceptionType = typeof(IOException), View = "Error")] public ActionResult IOError() { // 訪問一個不存在的文件 System.IO.File.Open(@"D:\error.txt",System.IO.FileMode.Open); // 返回Index視圖 return View("Index"); } } }
2、路由配置如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace _3_異常過濾器 { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); // 新增路由配置 routes.MapRoute( name: "Default2", url: "{controller}/{action}/{a}/", defaults: new { controller = "Home", action = "Index", a=0,b=0 } ); } } }
3、配置文件如下:
<system.web> <compilation debug="true" targetFramework="4.6.1" /> <httpRuntime targetFramework="4.6.1" /> <httpModules> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" /> </httpModules> <!--customErrors配置節(jié)mode的屬性值必須為On--> <customErrors mode="On"> </customErrors> </system.web>
4、運行結果
URL:http://localhost:21868/error/index/8/4
結果:
URL:http://localhost:21868/error/index/8/0
結果:
URL:http://localhost:21868/error/DbError
結果:
URL:http://localhost:21868/error/IOError
結果:
在同一個控制器或Action方法上可以通過HandleError處理多個異常,通過Order屬性決定捕獲的先后順序,但最上面的異常必須是下面異常的同類級別或子類。如下圖所示:
上面的程序可以修改成如下的代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using System.IO; namespace _3_異常過濾器.Controllers { [HandleError(Order =1, ExceptionType = typeof(SqlException), View = "Error")] [HandleError(Order =2, ExceptionType = typeof(IOException), View = "Error")] [HandleError(Order =3)] //不指定View,默認跳轉到Share下面的Error視圖 public class ErrorController : Controller { public ActionResult Index(int a,int b) { int c = a / b; ViewData["Result"] = c; return View(); } /// <summary> /// 測試數據庫異常 /// </summary> /// <returns></returns> public ActionResult DbError() { // 錯誤的連接字符串 SqlConnection conn = new SqlConnection(@"Initial Catalog=StudentSystem; Integrated Security=False;User Id=sa;Password=******;Data Source=127.0.0.1"); conn.Open(); // 返回Index視圖 return View("Index"); } /// <summary> /// IO異常 /// </summary> /// <returns></returns> public ActionResult IOError() { // 訪問一個不存在的文件 System.IO.File.Open(@"D:\error.txt",System.IO.FileMode.Open); // 返回Index視圖 return View("Index"); } } }
在上面的示例中,捕獲異常的時候只是跳轉到了Error視圖,如果我們想獲取異常的具體信息該怎么辦呢?如下圖所示:
查看MVC源碼,可以發(fā)現(xiàn)HandleError返回的是HandleErrorInfo類型的model,利用該model可以獲取異常的具體信息,修改Error視圖頁面如下:
結果:
到此這篇關于ASP.NET MVC異常過濾器用法的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
ASP.NET MVC中jQuery與angularjs混合應用傳參并綁定數據
這篇文章主要介紹了ASP.NET MVC中jQuery與angularjs混合應用傳參并綁定數據,需要的朋友可以參考下2017-06-06基于MVC4+EasyUI的Web開發(fā)框架之附件上傳組件uploadify的使用
這篇文章主要介紹了基于MVC4+EasyUI的Web開發(fā)框架之附件上傳組件uploadify的使用,需要的朋友可以參考下2017-08-08.net mvc頁面UI之Jquery博客日歷控件實現(xiàn)代碼
最近在做一個博客系統(tǒng),其他需要用到博客日歷控件,網上搜索了很多資料,其中大部分都是javascript的,經過總結使用jquery實現(xiàn)了博客日歷效果。代碼如下2013-09-09ASP.NET中RadioButtonList綁定后臺數據后觸發(fā)點擊事件
這篇文章主要介紹了ASP.NET中RadioButtonList綁定后臺數據后觸發(fā)點擊事件的相關資料,感興趣的小伙伴們可以參考一下2016-05-05擴展ASP.NET MVC三層框架且使用StructureMap實現(xiàn)依賴注入1-Model層
本篇文章將向大家介紹如何添加Service和Repository層并且使用StructureMap把Service層注入到Controller,把Repository注入到Service層。2013-04-04