ASP.NET MVC異常過濾器用法
我們平常在程序里面為了捕獲異常,會(huì)加上try-catch-finally代碼,但是這樣會(huì)使得程序代碼看起來很龐大,在MVC中我們可以使用異常過濾器來捕獲程序中的異常,如下圖所示:
使用了異常過濾器以后,我們就不需要在Action方法里面寫Try -Catch-Finally這樣的異常處理代碼了,而把這份工作交給HandleError去做,這個(gè)特性同樣可以應(yīng)用到Controller上面,也可以應(yīng)用到Action方面上面。
注意:
使用異常過濾器的時(shí)候,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> /// 測試數(shù)據(jù)庫異常 /// </summary> /// <returns></returns> [HandleError(ExceptionType = typeof(SqlException), View = "Error")] public ActionResult DbError() { // 錯(cuò)誤的連接字符串 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() { // 訪問一個(gè)不存在的文件 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、運(yùn)行結(jié)果
URL:http://localhost:21868/error/index/8/4
結(jié)果:
URL:http://localhost:21868/error/index/8/0
結(jié)果:
URL:http://localhost:21868/error/DbError
結(jié)果:
URL:http://localhost:21868/error/IOError
結(jié)果:
在同一個(gè)控制器或Action方法上可以通過HandleError處理多個(gè)異常,通過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,默認(rèn)跳轉(zhuǎn)到Share下面的Error視圖 public class ErrorController : Controller { public ActionResult Index(int a,int b) { int c = a / b; ViewData["Result"] = c; return View(); } /// <summary> /// 測試數(shù)據(jù)庫異常 /// </summary> /// <returns></returns> public ActionResult DbError() { // 錯(cuò)誤的連接字符串 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() { // 訪問一個(gè)不存在的文件 System.IO.File.Open(@"D:\error.txt",System.IO.FileMode.Open); // 返回Index視圖 return View("Index"); } } }
在上面的示例中,捕獲異常的時(shí)候只是跳轉(zhuǎn)到了Error視圖,如果我們想獲取異常的具體信息該怎么辦呢?如下圖所示:
查看MVC源碼,可以發(fā)現(xiàn)HandleError返回的是HandleErrorInfo類型的model,利用該model可以獲取異常的具體信息,修改Error視圖頁面如下:
結(jié)果:
到此這篇關(guān)于ASP.NET MVC異常過濾器用法的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- ASP.NET過濾器的應(yīng)用方法介紹
- asp.net?core?MVC?全局過濾器之ExceptionFilter過濾器(1)
- Asp.Net MVC學(xué)習(xí)總結(jié)之過濾器詳解
- asp.net core MVC 過濾器之ActionFilter過濾器(2)
- ASP.NET Core MVC 過濾器的使用方法介紹
- ASP.NET mvc4中的過濾器的使用
- ASP.NET Core MVC 過濾器(Filter)
- ASP.NET?MVC授權(quán)過濾器用法
- ASP.NET MVC自定義異常過濾器
- ?ASP.NET Core 模型驗(yàn)證過濾器的兩種實(shí)現(xiàn)方法
相關(guān)文章
ASP.NET MVC中jQuery與angularjs混合應(yīng)用傳參并綁定數(shù)據(jù)
這篇文章主要介紹了ASP.NET MVC中jQuery與angularjs混合應(yīng)用傳參并綁定數(shù)據(jù),需要的朋友可以參考下2017-06-06基于MVC4+EasyUI的Web開發(fā)框架之附件上傳組件uploadify的使用
這篇文章主要介紹了基于MVC4+EasyUI的Web開發(fā)框架之附件上傳組件uploadify的使用,需要的朋友可以參考下2017-08-08asp.net中c#自定義事件的實(shí)現(xiàn)方法詳解
這篇文章主要介紹了asp.net中c#自定義事件的實(shí)現(xiàn)方法,較為詳細(xì)的分析了自定義實(shí)現(xiàn)的各個(gè)步驟的具體實(shí)現(xiàn)思路與技巧,并給出了一個(gè)完整的實(shí)例總結(jié),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2014-12-12.net mvc頁面UI之Jquery博客日歷控件實(shí)現(xiàn)代碼
最近在做一個(gè)博客系統(tǒng),其他需要用到博客日歷控件,網(wǎng)上搜索了很多資料,其中大部分都是javascript的,經(jīng)過總結(jié)使用jquery實(shí)現(xiàn)了博客日歷效果。代碼如下2013-09-09在ASP.net中保存/取出圖片入/從SQL數(shù)據(jù)庫
在ASP.net中保存/取出圖片入/從SQL數(shù)據(jù)庫...2006-09-09vs.net 2010 擴(kuò)展插件小結(jié) 提高編程效率
本文價(jià)紹了幾款Visual Studio提供的插件,提高我們的編程效率。2011-03-03Web API身份認(rèn)證解決方案之Basic基礎(chǔ)認(rèn)證
本文詳細(xì)講解了Web API身份認(rèn)證解決方案之Basic基礎(chǔ)認(rèn)證,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03ASP.NET中RadioButtonList綁定后臺數(shù)據(jù)后觸發(fā)點(diǎn)擊事件
這篇文章主要介紹了ASP.NET中RadioButtonList綁定后臺數(shù)據(jù)后觸發(fā)點(diǎn)擊事件的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-05-05擴(kuò)展ASP.NET MVC三層框架且使用StructureMap實(shí)現(xiàn)依賴注入1-Model層
本篇文章將向大家介紹如何添加Service和Repository層并且使用StructureMap把Service層注入到Controller,把Repository注入到Service層。2013-04-04