欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ASP.NET MVC異常過濾器用法

 更新時(shí)間:2022年03月08日 15:06:42   作者:.NET開發(fā)菜鳥  
本文詳細(xì)講解了ASP.NET MVC異常過濾器的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

我們平常在程序里面為了捕獲異常,會(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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論