0
点赞
收藏
分享

微信扫一扫

mvc4自定义异常过滤器核心代码

建立Mvc4 基本 项目

1.在Models目录下,创建自定义异常类:

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

namespace EditorTemplateDemo.Models
{
    public class MyExceptAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            //base.OnException(filterContext);
            if (!filterContext.ExceptionHandled)
            {
                //获取出现异常的controller名和action名,用于记录
                string controllerName = (string)filterContext.RouteData.Values["controller"];
                string actionName = (string)filterContext.RouteData.Values["action"];
                //定义一个HandErrorInfo,用于Error视图展示异常信息
                HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                ViewResult result = new ViewResult
                {
                    ViewName = this.View,
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model)  //定义ViewData,泛型
                };
                filterContext.Result = result;
                filterContext.ExceptionHandled = true;
            }
        }

    }
}

2.创建Action:

  [MyExcept(View ="ErrorTip")]
  public ActionResult TestExcept()
  { 
	throw new NullReferenceException("测试抛出异常!");
  }

3.创建View:

ErrorTip.cshtml:

@model System.Web.Mvc.HandleErrorInfo
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>异常</title>
</head>
<body>
    <p>
        抛错控制器:<b>@Model.ControllerName</b> 抛错方法:<b>@Model.ActionName</b> 抛错类型:<b>
            @Model.Exception.GetType().Name
    </b>
</p>
<p>
    异常信息:<b>@Model.Exception.Message</b>
</p>
<p>
    堆栈信息:
</p>
<pre>@Model.Exception.StackTrace</pre>
</body>
</html>

4.添加修改Action:

 [MyExcept(View ="ErrorTip")]
 public ActionResult TestExcept()
 {
    throw new NullReferenceException("测试抛出异常!");
 }

测试:

启动后,地址栏中输入/Home/TestExcept,回车后,查看异常界面。

举报

相关推荐

0 条评论