C# MVC 错误跳转指定404 页面

C# MVC 错误跳转指定404 页面

前言

跳转方法有两种,第一种是修改配置文件,第二中是在Global.assx中添加Application_Error处理方法。

方法一步骤:(Application_Error)

一、先关闭自定义错误,将Web.config配置文件中customErrors节点的mode设置为Off,注意大小写

     
    
    
    
  

二、取消在GlobalFilterGlobalFilterGlobalFilter全局过滤器中取消HandleErrorAttribute的注册:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //filters.Add(new HandleErrorAttribute());
    }
}

三、在Golbal.assx重写Application_Error处理方法

protected void Application_Error(Object sender, EventArgs e)
{
    Exception lastError = Server.GetLastError();
    if (lastError != null)
    {
        //异常信息
        string strExceptionMessage = string.Empty;
        //对HTTP 404做额外处理,其他错误全部当成500服务器错误
        HttpException httpError = lastError as HttpException;
        if (httpError != null)
        {
            //获取错误代码
            int httpCode = httpError.GetHttpCode();
            strExceptionMessage = httpError.Message;
            if (httpCode == 400 || httpCode == 404)
            {
                Response.StatusCode = 404;
                //跳转到指定的静态404信息页面,根据需求自己更改URL
                Response.WriteFile("~/HttpError/404.html");
                Server.ClearError();
                return;
            }
        }
        strExceptionMessage = lastError.Message;
        /*-----------------------------------------------------
         * 此处代码可根据需求进行日志记录,或者处理其他业务流程
         * ---------------------------------------------------*/
        /*
         * 跳转到指定的http 500错误信息页面
         * 跳转到静态页面一定要用Response.WriteFile方法                 
         */
        Response.StatusCode = 500;
        Response.WriteFile("~/HttpError/500.html");
        //一定要调用Server.ClearError()否则会触发错误详情页(就是黄页)
        Server.ClearError();
        Server.Transfer("~/HttpError/500.aspx");
    }
}

编写Application_Error事件的代码需要注意的地方

1、一定要取消GlobalFilter全局过滤器中HandleErrorAttribute的注册,也要注意检查项目中是否有其他全局过滤器对异常进行处理的,防止HTTP 500类型的服务器错误不会触发Application_Error事件(其他类型错误依然可触发)。

2、无论最终处理的流程如何,在流程结束或者响应输出的地方,一定要调用Server.ClearError()方法清空异常,否则异常错误依然处于未被处理的状态,如果customErrors mode=”On”,那么异常会被自定义错误模块处理,除非本意就是要使用这种方式跳转到错误页。

3、如果要跳转到静态的自定义错误页面中,请使用Response.WriteFile(string filename)方法,最后设置下HTTP状态码

4、如果想要使用Server.Transfer(string path)方法跳转到自定义的错误页面,这里有两点需要注意:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注