For 404 and 500 errors, we want to define a more user-friendly page.
Example
When visiting the following address:
Http://localhost/aaaa/bbb/ccc/ddd/eee/fff/ggg
The URL of the browser does not change, still is
Http://localhost/aaaa/bbb/ccc/ddd/eee/fff/ggg
But the page shows our custom error page.
First, add the following nodes in Web. config.
<system.webserver> <httperrorsErrormode= "Custom"> <!--Jump 404 Page - <RemoveStatusCode= "404"Substatuscode= '-1 ' /> <ErrorStatusCode= "404"Path= "/error/404"Prefixlanguagefilepath=""Responsemode= "Executeurl" /> </httperrors> </system.webserver>
which
Path= "/error/404"
The value "/error/404" of Path is the URL address of the error page and can be defined by itself.
When a 404 error occurs, it jumps to that address.
Second, create a 404 error controller.
namespacewebapplication1.controllers{usingSYSTEM.WEB.MVC; Public classErrorcontroller:controller {// //GET:/error/ PublicActionResult Error404 () {//The "~/views/shared/error.cshtml" page is used here. returnView ("Error"); } }}
To add a routing rule:
namespacewebapplication1{usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingsystem.web; usingSYSTEM.WEB.MVC; usingSystem.Web.Routing; Public classRouteconfig { Public Static voidregisterroutes (routecollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); Routes. MapRoute ("error.404", "error/404", New{action ="Error404", CONTROLLER ="Error" } ); //routes. MapRoute (//Name: "Default",//URL: "{controller}/{action}/{id}",//defaults:new {controller = "Home", action = "Index", id = urlparameter.optional}//); } }}
Second, create a filter that is designed to handle exceptions.
namespacewebapplication1.filters{usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingsystem.web; usingSYSTEM.WEB.MVC; Public classCustomhandleerrorattribute:handleerrorattribute {/// <summary> ///exception handling. /// </summary> /// <param name= "Filtercontext" ></param> Public Override voidonexception (Exceptioncontext filtercontext) {if(Filtercontext.exception! =NULL) { //returns a 500 error. Filtercontext.result =NewViewResult {ViewName=View, Mastername=Master,}; Filtercontext.exceptionhandled=true; FilterContext.HttpContext.Response.Clear (); FilterContext.HttpContext.Response.StatusCode=404; FilterContext.HttpContext.Response.TrySkipIisCustomErrors=true; return; } Base. Onexception (Filtercontext); } }}
Since ASP. NET MVC already defines "Handleerrorattribute", just inherit and rewrite the "Onexception" method.
On the error.cshtml page, add:
" 404 Not Found ";
Otherwise, the page status is incorrect.
Complete, the "~/views/shared/error.cshtml" page is now used regardless of the 404 or 500 error.
:
Http://files.cnblogs.com/files/cjnmy36723/404%E4%B8%8E500%E9%94%99%E8%AF%AF%E9%A1%B5%E9%9D%A2%E6%BC%94%E7%A4%BA.rar
Custom 404 and 500 error pages, URL addresses are not redirected.