日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

ASP.NET?MVC異常過濾器用法_實用技巧

作者:.NET開發(fā)菜鳥 ? 更新時間: 2022-05-08 編程語言

我們平常在程序里面為了捕獲異常,會加上try-catch-finally代碼,但是這樣會使得程序代碼看起來很龐大,在MVC中我們可以使用異常過濾器來捕獲程序中的異常,如下圖所示:

使用了異常過濾器以后,我們就不需要在Action方法里面寫Try -Catch-Finally這樣的異常處理代碼了,而把這份工作交給HandleError去做,這個特性同樣可以應(yīng)用到Controller上面,也可以應(yīng)用到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();
        }

        /// 
        /// 測試數(shù)據(jù)庫異常
        /// 
        /// 
        [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");
        }

        /// 
        /// IO異常
        /// 
        /// 
        [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}/{b}",
              defaults: new { controller = "Home", action = "Index", a=0,b=0 }
          );
        }
    }
}

3、配置文件如下:


    
    
    
      
    
    
        
    

4、運行結(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é)果:

在同一個控制器或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,默認跳轉(zhuǎn)到Share下面的Error視圖
    public class ErrorController : Controller
    {
        public ActionResult Index(int a,int b)
        {
            int c = a / b;
            ViewData["Result"] = c;
            return View();
        }

        /// 
        /// 測試數(shù)據(jù)庫異常
        /// 
        /// 
        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");
        }

        /// 
        /// IO異常
        /// 
        /// 
        public ActionResult IOError()
        {
            // 訪問一個不存在的文件
            System.IO.File.Open(@"D:\error.txt",System.IO.FileMode.Open);
            // 返回Index視圖
            return View("Index");
        }
    }
}

在上面的示例中,捕獲異常的時候只是跳轉(zhuǎn)到了Error視圖,如果我們想獲取異常的具體信息該怎么辦呢?如下圖所示:

查看MVC源碼,可以發(fā)現(xiàn)HandleError返回的是HandleErrorInfo類型的model,利用該model可以獲取異常的具體信息,修改Error視圖頁面如下:

結(jié)果:

原文鏈接:https://www.cnblogs.com/dotnet261010/p/9005952.html

欄目分類
最近更新