首页 > 代码库 > MVC 全局异常处理及禁用显示头

MVC 全局异常处理及禁用显示头

MVC网站的global.asax中的Application_Start方法里,有这样一段代码:

 1    public class MvcApplication : System.Web.HttpApplication 2     { 3         protected void Application_Start() 4         { 5             AreaRegistration.RegisterAllAreas(); 6             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 7             RouteConfig.RegisterRoutes(RouteTable.Routes); 8             BundleConfig.RegisterBundles(BundleTable.Bundles); 9         }10     }

一、禁用显示头信息:

在global.asax中的Application_Start方法里添加如下代码:

MvcHandler.DisableMvcResponseHeader = true;

另外添加如下方法:

      /// <summary>        /// 移除响应头部信息        /// </summary>        protected void Application_PreSendRequestHeaders()        {            Response.Headers.Remove("Server");           //Remove Server Header               Response.Headers.Remove("X-AspNet-Version"); //Remove X-AspNet-Version Header        }

 

二、添加全局异常处理:

1、定义异常处理类,继承HandleErrorAttribute:

public class ExceptionLogAttribute:HandleErrorAttribute    {        /// <summary>        /// 触发异常时调用的方法        /// </summary>        /// <param name="filterContext"></param>        public override void OnException(ExceptionContext filterContext)        {            string message = string.Format("消息类型:{0}<br>消息内容:{1}<br>引发异常的方法:{2}<br>引发异常的对象:{3}。"                , filterContext.Exception.GetType().Name                , filterContext.Exception.Message                , filterContext.Exception.TargetSite                , filterContext.Exception.Source);            //登录用户            var loginUserId = Guid.Empty;            var loginInfo = filterContext.HttpContext.Session["userMdl"] as ViewModel.t_User_VModel;            if (loginInfo != null)            {                loginUserId = loginInfo.UserId;            }            var model=new JiaSoftOTOSystem.ViewModel.t_ExceptionLog_VModel{                ExceptionId=Guid.NewGuid(),                Title = filterContext.RouteData.GetRequiredString("controller")+"/"+filterContext.RouteData.GetRequiredString("action"),                Messge = message,                CreationTime=DateTime.Now,                CreatedByUserId = loginUserId            };            //将 ex 错误对象记录到日志            new JiaSoftOTOSystem.BLL.t_ExceptionLog_BLL().Add(model);            base.OnException(filterContext);        }    }

 

2、然后在global.asax中的Application_Start方法里注册事件 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)中添加全局异常处理类的注册:

 public class FilterConfig    {        public static void RegisterGlobalFilters(GlobalFilterCollection filters)        {            // 自定义异常类,继承自HandleError,将异常信息写入日志            filters.Add(new ExceptionLogAttribute());            //默认的异常记录类            filters.Add(new HandleErrorAttribute());        }    }

全局异常处理添加完毕。

 

MVC 全局异常处理及禁用显示头