最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

ASP.NET MVC異常過(guò)濾器用法

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

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

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

注意:

使用異常過(guò)濾器的時(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_異常過(guò)濾器.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>
        /// 測(cè)試數(shù)據(jù)庫(kù)異常
        /// </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()
        {
            // 訪問(wèn)一個(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_異常過(guò)濾器
{
    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方法上可以通過(guò)HandleError處理多個(gè)異常,通過(guò)Order屬性決定捕獲的先后順序,但最上面的異常必須是下面異常的同類級(jí)別或子類。如下圖所示:

上面的程序可以修改成如下的代碼:

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_異常過(guò)濾器.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>
        /// 測(cè)試數(shù)據(jù)庫(kù)異常
        /// </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()
        {
            // 訪問(wèn)一個(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視圖頁(yè)面如下:

結(jié)果:

到此這篇關(guān)于ASP.NET MVC異常過(guò)濾器用法的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 使用.NET8實(shí)現(xiàn)Web API的項(xiàng)目實(shí)踐

    使用.NET8實(shí)現(xiàn)Web API的項(xiàng)目實(shí)踐

    ASP.NET Web API是一種框架,用于輕松構(gòu)建可以由多種客戶端訪問(wèn)的 HTTP服務(wù),本文主要介紹了使用.NET8實(shí)現(xiàn)Web API的項(xiàng)目實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-05-05
  • Asp.net MVC SignalR來(lái)做實(shí)時(shí)Web聊天實(shí)例代碼

    Asp.net MVC SignalR來(lái)做實(shí)時(shí)Web聊天實(shí)例代碼

    本篇文章主要介紹了Asp.net SignalR來(lái)做實(shí)時(shí)Web聊天實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • 使用dotnet-dump 查找 .net core 3.0 占用CPU 100%的原因解析

    使用dotnet-dump 查找 .net core 3.0 占用CPU 100%的原因解析

    這篇文章主要介紹了使用dotnet-dump 查找 .net core 3.0 占用CPU 100%的原因,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-06-06
  • Asp.net后臺(tái)調(diào)用js 2種方法

    Asp.net后臺(tái)調(diào)用js 2種方法

    這篇文章主要介紹了Asp.net后臺(tái)調(diào)用js的二種方法,大家參考使用吧
    2013-11-11
  • 在dropDownList中實(shí)現(xiàn)既能輸入一個(gè)新值又能實(shí)現(xiàn)下拉選的代碼

    在dropDownList中實(shí)現(xiàn)既能輸入一個(gè)新值又能實(shí)現(xiàn)下拉選的代碼

    在dropDownList中實(shí)現(xiàn)既能輸入一個(gè)新值,又能實(shí)現(xiàn)下拉選項(xiàng),想必很多的朋友已經(jīng)為此功能按耐不住了吧,接下來(lái)與大家分享下如何實(shí)現(xiàn),感興趣的朋友可以參考下哈
    2013-04-04
  • 最新評(píng)論

    濉溪县| 永兴县| 襄城县| 沭阳县| 顺昌县| 屯门区| 深州市| 阳东县| 南江县| 长白| 姚安县| 砀山县| 尼木县| 西贡区| 博白县| 乐昌市| 广宁县| 察隅县| 翁源县| 邹城市| 连州市| 咸丰县| 丰原市| 晋州市| 翁牛特旗| 电白县| 邻水| 蒙阴县| 宝坻区| 永靖县| 宝鸡市| 张北县| 宜章县| 呼伦贝尔市| 微山县| 永平县| 深水埗区| 盱眙县| 贵港市| 观塘区| 清水河县|