直接進入正題。 在HomeController中有一個NotFound的Action方法。 public ActionResult NotFound() { return View(); } 對應的視圖 @{ Layout = null; } <!DOCTYPE html> <html> <head ...
直接進入正題。
在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
當前臺訪問存在的頁面或資源時:
當訪問不存在的非靜態資源時,顯示自定義錯誤頁
當訪問不存在的靜態資源時: