在Global中写一个Application_Error捕捉错误路由并重定向到Not Found页面。这里是全局性抓取错误路由,此处还可以写由错误路由导致访问失败的日志记录。
protected void Application_Error(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
var currentController = "";
var currentAction = "";
var currentRouterData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)); if (currentRouterData != null)
{
if (currentRouterData.Values["controller"] != null && !string.IsNullOrEmpty(currentRouterData.Values["controller"].ToString()))
{
currentController = currentRouterData.Values["controller"].ToString();
} if (currentRouterData.Values["action"] != null && !string.IsNullOrEmpty(currentRouterData.Values["action"].ToString()))
{
currentAction = currentRouterData.Values["action"].ToString();
}
} var ex = Server.GetLastError();
//record error log here. var controller = new ErrorController();
var routeData = new RouteData();
var action = "Index"; if (ex is HttpException)
{
var httpEx = ex as HttpException; switch (httpEx.GetHttpCode())
{
case :
action = "Not Found";
Response.Redirect("/Error/index");
break;
} httpContext.ClearError();
httpContext.Response.Clear();
httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : ;
httpContext.Response.TrySkipIisCustomErrors = true; routeData.Values["controller"] = "Error";
routeData.Values["action"] = action;
}
}
NotFound页面:
@{
Layout = null;
} <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex,nofollow">
<meta name="viewport" content="width=device-width,maximum-scale=1,user-scalable=no,minimal-ui">
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800&subset=latin,latin-ext">
<link rel="stylesheet" type="text/css" href="https://cdn.travel.sygic.com/travel.sygic.com_lp/css/404.css?4aed45ea0fff817941fb48877a968cf6cc920152">
<title>
Not found
</title> </head>
<body>
<div class="stars"></div> <div class="sun-moon">
<div class="sun"></div>
<div class="moon"></div>
</div> <div id="js-hills" class="background hills"></div>
<div id="js-country" class="background country"></div>
<div id="js-foreground" class="background foreground"></div> <div class="error-content">
Sorry, that page never returned<br>
from a Consultant to the <a href="/go/region:377">Marykay</a>.
</div> <a href="https://www.marykay.com.cn/" class="button-home">Go home</a> <div class="code">
<span></span>
<span></span>
<span></span>
</div>
</body>
</html>
在地址栏输入错误的路由-》效果
404页面来源于:
错误的艺术!20个创意的404错误页面设计
http://www.cnblogs.com/lhb25/p/creative-examples-of-404-error-pages.html