MVC4 自定义错误页面(转)

原文链接: http://www.cnblogs.com/xcsn/p/5647875.html

一、概述

MVC4框架自带了定义错误页,该页面位于Shared/Error,该页面能够显示系统未能捕获的异常,如何才能使用该页面;

二、使用步骤:

1、配置WebConfig文件,在System.Web节点下加上

<customErrors mode="On"  defaultRedirect="~/Shared/Error" />

翻阅一些大神写的博客,在他们的博客中指出defaultRedirect是指向错误页面的URL,可是经过本人测试的时候,发现在MVC4中这种说法并不准,在MVC中,有一套默认的机制(这部分代码被微软封装,无法阅读),该机制能够把错误信息通过HandleError属性指向Shared/Error页面,也就是说配置System.Web节点,可以省略defaultRedirect

customErrors mode="On"/>   

2、Global文件,添加HandleEffor属性

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
 {
       filters.Add(new HandleErrorAttribute(),1);            
 }

在Global定义之后,也就是全局定义,其他Action和Control都不需要定义,默认使用HandleError控制属性;

这样就可以使用MVC4中系统默认的Error页面;

三、自定义错误页面

  有些时候,我们想使用自定义的错误页面,该怎么处理那,翻页其他大牛写的博客,看到有这种方式,自定义属性Class继承FileterAttribute,重写OnException方法,代码如下

复制代码
public class BaseHandleErrorAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled == true)
            {
                HttpException httpExce = filterContext.Exception as HttpException;
                if (httpExce != null && httpExce.GetHttpCode() != 500)//为什么要特别强调500 因为MVC处理HttpException的时候,如果为500 则会自动将其ExceptionHandled设置为true,那么我们就无法捕获异常
                {
                    return;
                }
            }
            Exception exception = filterContext.Exception;            
            if (exception != null)
            {
                HttpException httpException = exception as HttpException;
                if (httpException != null)
                {
                    //网络错误
                    filterContext.Controller.ViewBag.UrlRefer = filterContext.HttpContext.Request.UrlReferrer;
                    int DataEroorCode = httpException.GetHttpCode();
                    if (DataEroorCode == 404)
                    {
                        filterContext.HttpContext.Response.Redirect("~/SysError/404");
                    }
                    else if (DataEroorCode == 500)
                    {
                        filterContext.HttpContext.Response.Redirect("~/SysError/500");
                    }
                    else
                        filterContext.HttpContext.Response.Redirect("~/SysError/" + DataEroorCode);

                    //写入日志 记录
                    filterContext.ExceptionHandled = true;//设置异常已经处理
                }
                else
                {
                    //编程或者系统错误,不处理,留给HandError处理
                }
            }                     
        }
    }
复制代码

将该属性注册到全局Global中,定义铺货异常等级

复制代码
      public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new BaseHandleErrorAttribute(),0);

            filters.Add(new HandleErrorAttribute(),1);
            
        }
复制代码

当然我们也可以不使用MVC框架自带的Error页面,定义一个Error404,如何使用这个页面那 ,起始也挺简单的,代码如下

复制代码
      public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new BaseHandleErrorAttribute(),0);

            filters.Add(new HandleErrorAttribute(View="Error404"),1);
            
        }
复制代码

四、遇到问题总结

1、遇到重定向,URL指向aspxerrorpath,如:

http://local:8090/error/error.htm?aspxerrorpath=/cmt/p/3789549.html

出现这个问题的主要原因:

1>、Global没有添加 

filters.Add(new HandleErrorAttribute(View="Error404"))

2>、Shared目录没有Error页面;

3>、如果存在Error页面,但是页面是用了布局Layout,组成的Error页面存在错误,比如ModeView数据不对等,需要详查;

2、自定义Error的其他方式

翻页其他大牛写的文章时候,返现也可以使用Gloal中的Application_Error事件方法处理,比如博主@dudu写的异常处理方式;

代码粘贴如下:

复制代码
protected void Application_Error(Object sender, EventArgs e)
{
    var lastError = Server.GetLastError();
    if (lastError != null)
    {
        var httpError = lastError as HttpException;
        if (httpError != null)
        {
            //ASP.NET的400与404错误不记录日志,并都以自定义404页面响应
            var httpCode = httpError.GetHttpCode();
            if (httpCode == 400 || httpCode == 404)
            {
                Response.StatusCode = 404;//在IIS中配置自定义404页面
                Server.ClearError();
                return;
            }
            Logger.Default.Error("Application_Error_" + httpCode, httpError);
        }

        //对于路径错误不记录日志,并都以自定义404页面响应
        if (lastError.TargetSite.ReflectedType == typeof(System.IO.Path))
        {
            Response.StatusCode = 404;
            Server.ClearError();
            return;
        }

        Logger.Default.Error("Application_Error", lastError);
        Response.StatusCode = 500;
        Server.ClearError();
    }
}
复制代码

实现样式多样,只要实现功能就是最好;

原文:http://www.cnblogs.com/xibei666/p/5153807.html

转载于:https://www.cnblogs.com/xcsn/p/5647875.html

猜你喜欢

转载自blog.csdn.net/weixin_30471065/article/details/94793520