zoukankan      html  css  js  c++  java
  • Asp.net MVC3 异常全局过滤器处理


    1、建立异常全局过滤器处理机制,在Gloabal.asax.cs文件中,有如下代码块:

         public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new HandleErrorAttribute());//主要就是这样一个类
            }

    2、查看源码可以看到:

     public class HandleErrorAttribute : FilterAttribute, IExceptionFilter
      {
        /// <summary>
        /// Called when an exception occurs.
        /// </summary>
        /// <param name="filterContext">The action-filter context.</param><exception cref="T:System.ArgumentNullException">The <paramref name="filterContext"/> parameter is null.</exception>
        public virtual void OnException(ExceptionContext filterContext);//看到这里我们就有办法进行自定义处理了
        /// <summary>
        /// Gets or sets the type of the exception.
        /// </summary>
        /// 
        /// <returns>
        /// The type of the exception.
        /// </returns>
        public Type ExceptionType { get; set; }
        /// <summary>
        /// Gets or sets the master view for displaying exception information.
        /// </summary>
        /// 
        /// <returns>
        /// The master view.
        /// </returns>
        public string Master { get; set; }
        /// <summary>
        /// Gets the unique identifier for this attribute.
        /// </summary>
        /// 
        /// <returns>
        /// The unique identifier for this attribute.
        /// </returns>
        public override object TypeId { get; }
        /// <summary>
        /// Gets or sets the page view for displaying exception information.
        /// </summary>
        /// 
        /// <returns>
        /// The page view.
        /// </returns>
        public string View { get; set; }
      }

    3、我们新建一个类,并且继承自HandleErrorAttribute,然后重写OnException方法

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using log4net;
    
    namespace MyEFTest.Models
    {
        public class MyHandlerExceptionAttribute : HandleErrorAttribute
        {
            public override void OnException(ExceptionContext filterContext)
            {
                base.OnException(filterContext);
                //记录错误信息
                ILog log = log4net.LogManager.GetLogger(typeof (MyHandlerExceptionAttribute).FullName);
                log.Error(filterContext.Exception.ToString());
                //让当前请求 跳转到首页,或者错误页面
                filterContext.HttpContext.Response.Redirect("/ErrorPage.htm");//ErrorPage是自定义的错误页面
            }
        }
    }

    4、这样就OK了,只要程序遇到异常,就会跳到错误页面。

  • 相关阅读:
    第十一节 1虚拟路径 简单
    第十一节 4Server对象 简单
    第十节 19验证码案例 简单
    第十节 19爆力注册 简单
    第十节 23行删除例子讲解请求处理响应 简单
    第十节 18暴力破解及机器人注册原理 简单
    第十一节 2Request对象 简单
    礼物
    笔记本电脑与漂亮老婆
    一场傻B的晚会
  • 原文地址:https://www.cnblogs.com/tianboblog/p/3248120.html
Copyright © 2011-2022 走看看