Several ways to customize error pages and show error pages under ASP.

Source: Internet
Author: User

In the website operation, the error is unavoidable, the error page generation is also indispensable.

These days to see a lot of bo friends of the article, I want to summarize what I learned from and the actual configuration.

First, we need to know the source of the error page, one of ours. NET platform, the one that the Web site relies on is thrown by the host, in general we rely on the host is IIS.

Error page entry in IIS:

The error code must not be unfamiliar.

Here is the error page that is thrown when the required resource is not found on the server, where you can set the error page that needs to be displayed, simply add the scheduled error page to the server and configure the path under the specified status code.

This is the request in IIS, which has not yet fully entered into ASP. NET MVC, which needs to understand what is not fully entered, the iis7+ version, does not depend on the identity information at the end of the request path, is processed using the UrlRoutingModule in MVC, When we configure the route for MVC, the first one:

Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");

is to isolate the usage files within the non-MVC, and if only the files on the server are requested, then the route will be filtered here so that it does not match the specific routing information.

Just say hello to MVC and then go, without getting into MVC and doing things.

The second is to go into the jurisdiction of ASP. NET MVC and then make an error in it and jump to the error page we configured in the program.

First of all, I learned from Bo friends, see a few ways.

The first is through the Customerror configuration in Web. config.

<mode= "on"  defaultredirect= "~/error/errorpage">      <statusCode= "404"  redirect= "~/error/ ErrorPage404 "/></customErrors>

But this approach is not very acceptable, too simple, there is no abnormal information, and sometimes not effective, I do not like this way.

This is wrapped in a framework, the use of the third powerful way to be said to achieve, when there are exceptions and no capture, the final use of the third method automatically implemented.

The second is the use of handlererrorattribute characteristics, the use of AOP, when there is an anomaly, it will enter the specific implementation of this feature, and is registered in the Exceptionattribute responsibility.

namespacesassassin.web.core.filter{/// <summary>    ///exception handling log records using Message Queuing/// </summary>     Public classMyexceptionattribute:handleerrorattribute { Public StaticQueue<exception> Exceptionqueue =NewQueue<exception>();  Public Override voidonexception (Exceptioncontext filtercontext) {exceptionqueue.enqueue (filtercontext.exception); FilterContext.HttpContext.Response.Redirect ("~/errorpage/customerrorpage"); Base.        Onexception (Filtercontext); }    }}

Here, I can get the exception information, can also parse the specific cause of abnormal error, such as 404,500 ... This situation allows you to move it to a different custom error page, where I added a controller

Customerrorpagecontroller, dedicated to storing the error page, the original shared error.cshtml error page still exists.

I prefer this approach, where you can see the exception information, and you can design the error page that needs to jump.

The third way is also the most powerful, commonly known as "The last line of defense", from the global level to catch abnormal application_error

When the site is first launched, a special action is performed, Application_Start first, and only once. This is also an event in application.

        //        //Summary://ASP. Occurs before HTTP headers are sent to the client.          Public EventEventHandler presendrequestheaders; //        //Summary://occurs when the handler is selected to respond to the request.          Public EventEventHandler Maprequesthandler; //        //Summary://occurs when the application is released.          Public EventEventHandler disposed; //        //Summary://as the first event in the execution of the HTTP pipeline chain occurs, when ASP. NET requests respond.          Public EventEventHandler beginrequest; //        //Summary://occurs when the security module has established a user ID.          Public EventEventHandler AuthenticateRequest; //        //Summary://occurs when the security module has established a user ID.          Public EventEventHandler postauthenticaterequest; //        //Summary://occurs when the security module has authenticated user authentication.          Public EventEventHandler AuthorizeRequest; //        //Summary://occurs when the currently requested user has been authorized.          Public EventEventHandler postauthorizerequest; //        //Summary://occurs when an ASP. NET finishes authorization event so that a cached module that skips an event handler (for example, a page or XML Web service) executes the request to serve the cache.          Public EventEventHandler Resolverequestcache; //        //Summary://ASP. NET will bypass the execution of the current event handler and allow the cache module to handle requests from the cache when it occurs.          Public EventEventHandler Postresolverequestcache; //        //Summary://occurs before the content is sent to the client by ASP.          Public EventEventHandler presendrequestcontent; //        //Summary://occurs when ASP. NET has been mapped to the current request of the appropriate event handler.          Public EventEventHandler Postmaprequesthandler; //        //Summary://The System.Web.HttpApplication.LogRequest event occurs when ASP. NET has finished processing the event handler.          Public EventEventHandler postlogrequest; //        //Summary://occurs when the managed object associated with the request has been disposed.          Public EventEventHandler requestcompleted; //        //Summary://occurs when the request state (for example, session state) associated with the current request is obtained.          Public EventEventHandler postacquirerequeststate; //        //Summary://occurs before an event handler (for example, a page or XML Web service) is started by ASP.          Public EventEventHandler PreRequestHandlerExecute; //        //Summary://occurs when an ASP. NET event handler (for example, a page or XML Web service) finishes executing.          Public EventEventHandler PostRequestHandlerExecute; //        //Summary://occurs after ASP. NET finishes executing all the request event handlers. This event causes the state module to save the current state data.          Public EventEventHandler releaserequeststate; //        //Summary://occurs when ASP. NET has finished executing all request event handlers and the request state that stores the data.          Public EventEventHandler postreleaserequeststate; //        //Summary://occurs when ASP. NET finishes executing the event handler so that the cache module stores the response that will be used to serve the subsequent requests from the cache.          Public EventEventHandler Updaterequestcache; //        //Summary://occurs when ASP. NET finishes updating the cache module and stores the response that is used to provide service for subsequent requests from the cache.          Public EventEventHandler Postupdaterequestcache; //        //Summary://occurs before any log records for the current request are executed by ASP.          Public EventEventHandler logrequest; //        //Summary://when ASP. NET gets the current state associated with the current request (for example, session state).          Public EventEventHandler acquirerequeststate; //        //Summary://as the last event in the execution of the HTTP pipeline chain occurs, when an ASP. NET request responds.          Public EventEventHandler EndRequest; //        //Summary://occurs when an unhandled exception is thrown.          Public EventEventHandler Error;

Seeing the last event, when an unhandled exception occurs, is the last line of defense. If the exception is not captured in an AOP way, then application _error is on the scene.

In Global.asax, we can write this method.

        /// <summary>        ///Global exception handling can be completed/// </summary>        /// <param name= "Sender" ></param>        /// <param name= "E" ></param>        protected voidApplication_Error (Objectsender, EventArgs e) {            //code to run when an unhandled error occurs            varError =Server.GetLastError (); varCode = (Error isHttpException)? (Error asHttpException). Gethttpcode (): -; //If the error message is not logged HttpException            if(Code! =404)            {                //message or log logging error message here} Response.Write ("Error");            Server.ClearError (); stringPath =Request.path; Context.rewritepath (string. Format ("~/errors/http{0}", code),false); IHttpHandler HttpHandler=NewMvchttphandler ();            Httphandler.processrequest (Context); Context.rewritepath (Path,false); }

In this method, we can also get exception information, log or email notification,

You can also make the corresponding jump error page according to the error code.

You can also add additional information to the current error page.

It's very powerful.

If this method is not written, the default method of the framework encapsulation is leveraged. This is the way to help when the Customerror node is configured in Web. config.

There may be more and better ways. I want to learn and learn.

2017-11-19,望技术有成后能回来看见自己的脚步。

A few ways to customize error pages and show error pages under ASP. NET MVC

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.