码迷,mamicode.com
首页 > Web开发 > 详细

MVC 实现自定义404错误页

时间:2017-11-10 01:34:12      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:col   ring   contains   none   last   result   实现   images   app   

直接进入正题。

在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

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

技术分享

 

 

 

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

技术分享

 

 

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

技术分享

 

 

MVC 实现自定义404错误页

标签:col   ring   contains   none   last   result   实现   images   app   

原文地址:http://www.cnblogs.com/godbell/p/7811979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!