MVC 实现自定义404错误页

直接进入正题。

在HomeController中有一个NotFound的Action方法。

public ActionResult NotFound()
{
    return View();
}
View Code

对应的视图

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>出错了</title>
</head>
<body>
    <div style="text-align:center;font-size:1.5em"> 
        为什么受伤的总是我 o(╥﹏╥)o
    </div>
</body>
</html>
View Code

在Global.asax.cs中定义的Application_Error方法,在方法中获取错误并判断是否是静态资源的404错误,如果不是,则使用自定义的错误页显示

private readonly string[] staticFileExt = new string[] { ".axd", ".ashx", ".bmp", ".css", ".gif", ".htm", ".html", ".ico", ".jpeg", ".jpg", ".js", ".png", ".rar", ".zip",".woff",".ttf" ,".eot",".svg"};
View Code
protected void Application_Error()
{
    var error = Server.GetLastError() as HttpException;
    if (error!= null && error.GetHttpCode() == 404)
    {
        if (!IsStaticResource(Request))
        {
            Response.Clear();
            Server.ClearError();
            Response.TrySkipIisCustomErrors = true;

            IController controller = new HomeController();

            var routeData = new RouteData();
            routeData.Values.Add("controller", "Home");
            routeData.Values.Add("action", "NotFound");

            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
    }
}

private bool IsStaticResource(HttpRequest request)
{
    string extension = VirtualPathUtility.GetExtension(request.Path);
    return staticFileExt.Contains(extension);
}
View Code

当前台访问存在的页面或资源时:

 

 

 

当访问不存在的非静态资源时,显示自定义错误页

 

 

当访问不存在的静态资源时:

 

 

posted @ 2017-11-09 23:15  Jichan·Jong  阅读(1003)  评论(0编辑  收藏  举报