MVC implementation Custom 404 error page

Source: Internet
Author: User

Go straight to the chase.

There is a NotFound action method in HomeController.

 Public ActionResult NotFound () {    return  View ();}
View Code

The corresponding view

@{Layout = null;}<!DOCTYPE HTML><HTML><Head>    <MetaCharSet= "Utf-8" />    <Metaname= "Viewport"content= "Width=device-width" />    <title>Something went wrong.</title></Head><Body>    <Divstyle= "Text-align:center;font-size:1.5em">Why is the injury always Me O (╥﹏╥) o</Div></Body></HTML>
View Code

The Application_Error method, defined in Global.asax.cs, gets the error in the method and determines whether it is a 404 error for a static resource, and if not, uses the custom error page to display

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 station accesses a page or resource that exists:

Display a custom error page when accessing non-static resources that do not exist

When accessing a static resource that does not exist:

MVC implementation Custom 404 error page

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.