Implement custom 404 error pages in MVC, and customize 404 in mvc
Go to the topic.
There is a NotFound Action Method in HomeController.
public ActionResult NotFound(){ return View();}
View Code
View
@ {Layout = null ;}<! DOCTYPE html> View Code
The Application_Error method defined in Global. asax. cs gets an error in the method and determines whether it is a 404 error of a static resource. If not, the custom error page is displayed.
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
When the current server accesses an existing page or resource:
When accessing non-static resources that do not exist, the custom error page is displayed.
When you access a static resource that does not exist: