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

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

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

ASP.NET?MVC自定義異常過濾器_實用技巧

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

一、異常過濾器

異常篩選器用于實現(xiàn)IExceptionFilter接口,并在ASP.NET MVC管道執(zhí)行期間引發(fā)了未處理的異常時執(zhí)行。異常篩選器可用于執(zhí)行諸如日志記錄或顯示錯誤頁之類的任務(wù)。HandleErrorAttribute類是異常篩選器的一個示例。

先來看看HandleErrorAttribute類的定義:

#region 程序集 System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// D:\Practice\MVC\自定義異常過濾器\MVCCuetomerExcepFilter\packages\Microsoft.AspNet.Mvc.5.2.7\lib\net45\System.Web.Mvc.dll
#endregion

namespace System.Web.Mvc
{
    //
    // 摘要:
    //     表示一個特性,該特性用于處理由操作方法引發(fā)的異常。
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class HandleErrorAttribute : FilterAttribute, IExceptionFilter
    {
        //
        // 摘要:
        //     初始化 System.Web.Mvc.HandleErrorAttribute 類的新實例。
        public HandleErrorAttribute();

        //
        // 摘要:
        //     獲取或設(shè)置異常的類型。
        //
        // 返回結(jié)果:
        //     異常的類型。
        public Type ExceptionType { get; set; }
        //
        // 摘要:
        //     獲取或設(shè)置用于顯示異常信息的母版視圖。
        //
        // 返回結(jié)果:
        //     母版視圖。
        public string Master { get; set; }
        //
        // 摘要:
        //     獲取此特性的唯一標識符。
        //
        // 返回結(jié)果:
        //     此特性的唯一標識符。
        public override object TypeId { get; }
        //
        // 摘要:
        //     獲取或設(shè)置用于顯示異常信息的頁視圖。
        //
        // 返回結(jié)果:
        //     頁視圖。
        public string View { get; set; }

        //
        // 摘要:
        //     在發(fā)生異常時調(diào)用。
        //
        // 參數(shù):
        //   filterContext:
        //     操作篩選器上下文。
        //
        // 異常:
        //   T:System.ArgumentNullException:
        //     filterContext 參數(shù)為 null。
        public virtual void OnException(ExceptionContext filterContext);
    }
}

從代碼中可以看出HandleErrorAttribute繼承了IExceptionFilter接口,并且有一個虛方法,如果要自定義異常過濾器,只需要繼承HandleErrorAttribute類并重寫HandleErrorAttribute類里面的虛方法即可。

二、示例

1、創(chuàng)建異常類

新建一個ExceptionFilters類繼承自HandleErrorAttribute,并重寫OnException方法,代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCCuetomerExcepFilter.Extension
{
    /// 
    /// 異常過濾器
    /// 
    public class ExceptionFilters : HandleErrorAttribute
    {
        /// 
        /// 在異常發(fā)生時調(diào)用
        /// 
        /// 
        public override void OnException(ExceptionContext filterContext)
        {
            // 判斷是否已經(jīng)處理過異常
            if(!filterContext.ExceptionHandled)
            {
                // 獲取出現(xiàn)異常的controller和action名稱,用于記錄
                string strControllerName = filterContext.RouteData.Values["controller"].ToString();
                string strActionName = filterContext.RouteData.Values["action"].ToString();
                // 定義一個HandleErrorInfo,用于Error視圖展示異常信息
                HandleErrorInfo info = new HandleErrorInfo(filterContext.Exception, strControllerName, strActionName);

                ViewResult result = new ViewResult
                {
                    ViewName = this.View,
                    // 定義ViewData,泛型
                    ViewData = new ViewDataDictionary(info)
                };
                // 設(shè)置操作結(jié)果
                filterContext.Result = result;
                // 設(shè)置已經(jīng)處理過異常
                filterContext.ExceptionHandled = true;
            }
            //base.OnException(filterContext);
        }
    }
}

2、創(chuàng)建控制器

新建一個控制器,代碼如下:

using MVCCuetomerExcepFilter.Extension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCCuetomerExcepFilter.Controllers
{
    public class ExceptionController : Controller
    {
        // GET: Exception
        /// 
        /// View表示發(fā)生異常時指定的視圖
        /// 這里表示發(fā)生異常時使用ExceptionDetails視圖
        /// 
        /// 
        [ExceptionFilters(View =("ExceptionDetails"))]
        public ActionResult Index()
        {
            // 測試拋出異常
            throw new NullReferenceException("測試拋出的異常");
        }
    }
}

異常發(fā)生時使用ExceptionDetails視圖,所以在Shared文件夾里面新建ExceptionDetails視圖,代碼如下:


@model System.Web.Mvc.HandleErrorInfo
@{
    Layout = null;
}



    
    異常


    

拋錯控制器:@Model.ControllerName 拋錯方法:@Model.ActionName 拋錯類型: @Model.Exception.GetType().Name

異常信息:@Model.Exception.Message

堆棧信息:

@Model.Exception.StackTrace

三、測試

運行程序,訪問Exception控制器的Index方法,效果如下:

四、總結(jié)

上面的案例演示了一個自定義異常類,很明顯比HandleError要靈活,在自定義異常類里面可以寫很多與業(yè)務(wù)相關(guān)的代碼。

GitHub代碼地址:https://github.com/jxl1024/CustomerHandleErrorFilter

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

欄目分類
最近更新