Implement custom 404 error pages in MVC, and customize 404 in mvc

Source: Internet
Author: User

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:

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.