Methods for customizing error pages and displaying error pages under ASP. net mvc, asp. netmvc
During website operation, errors are inevitable, and the generation of error pages is also indispensable.
I have read many articles from Boyou over the past few days and want to summarize the configurations I have learned and configured in the real world.
First, you need to know the source of the error page. One is ours. NET platform throws. One is thrown by the host on which the website depends. Generally, the host on which we depend is IIS.
IIS error page entry:
The error codes must be no stranger.
Here is the error page that is thrown when the required resources cannot be found on the server. Here, you can set the error page to be displayed. You only need to add the predefined error page to the server, configure the path under the specified status code.
This is when the request is in IIS and has not completely entered asp.net mvc. here we need to understand what is not completely entered. In IIS7 + versions, it does not depend on the ID information at the end of the Request Path, the urlRoutingModule in mvc is used for processing. When we configure the mvc routing, the first one is as follows:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
It is to isolate non-mvc internal use files. If only files on the server are requested, the routing will be filtered here to make it not match the specific routing information.
I just said hello to mvc and then left. I didn't go into mvc to do things.
The second is to enter the jurisdiction of asp.net mvc, and an error occurs in it, that is, to jump to the error page we configured in the program.
First of all, let's talk about the methods I learned from Boyou.
The first is to use customError configuration in web. config.
<customErrors mode="On" defaultRedirect="~/Error/ErrorPage"> <error statusCode="404" redirect="~/Error/ErrorPage404" /></customErrors>
However, this method is not very acceptable. It is too simple, with no exception information, and sometimes does not work. I do not like this method very much.
This is encapsulated by the framework and implemented in the third powerful way to be discussed. When exceptions occur and are not captured, the third method will be used for automatic implementation.
The second method is to use the HandlerErrorAttribute feature and the AOP method. When an exception occurs, it will enter the specific implementation of this feature and the registered predictionattribute responsibility.
Namespace SAssassin. web. core. filter {/// <summary> /// the log for exception handling adopts the Message Queue method. /// </summary> public class MyExceptionAttribute: handleErrorAttribute {public static Queue <Exception> ExceptionQueue = new Queue <Exception> (); public override void OnException (ExceptionContext filterContext) {ExceptionQueue. enqueue (filterContext. exception); filterContext. httpContext. response. redirect ("~ /ErrorPage/CustomErrorPage "); base. OnException (filterContext );}}}
Here, I can get the exception information or parse the specific error cause, such as 404,500... you can transfer it to different custom error pages through this situation. Here I added a controller
CustomErrorPageController is used to store Error pages. The Error. cshtml Error page in the original Shared file still exists.
I prefer this method to see the exception information and design the error page to be redirected.
The third method is also the most powerful, commonly known as "the last line of defense", to capture exceptions at the global levelApplication_Error
When the website is started for the first time, a special action is executed. Application_start is executed first and only once. This is also an event in the Application.
//// Summary: // ASP. NET occurs before the HTTP header is sent to the client. Public event EventHandler PreSendRequestHeaders; // Summary: // occurs when the handler is selected to respond to the request. Public event EventHandler MapRequestHandler; /// Summary: // occurs when the application is released. Public event EventHandler Disposed; /// Abstract: // occurs as the first event in the HTTP pipeline chain executed when ASP. NET requests respond. Public event EventHandler BeginRequest; // Abstract: // the user ID created in the security module appears. Public event EventHandler AuthenticateRequest; // Abstract: // the user ID created in the security module. Public event EventHandler PostAuthenticateRequest; // Summary: // The Security Module has authenticated the user. Public event EventHandler AuthorizeRequest; // Summary: // the user of the current request has been authorized. Public event EventHandler PostAuthorizeRequest; // Abstract: // when ASP.. NET completes the authorization event so that requests from the cache that are skipped by the event handler (for example, a page or XML Web Service) to provide the cache module of the service occur. Public event EventHandler ResolveRequestCache; // Summary: // ASP. NET will bypass the execution of the current event handler and allow the cache module to process requests from the cache. Public event EventHandler PostResolveRequestCache; // Summary: // ASP. NET occurs before the content is sent to the client. Public event EventHandler PreSendRequestContent; // Summary: // when ASP. NET is mapped to the current request of the corresponding event handler. Public event EventHandler PostMapRequestHandler; /// Summary: // The System. Web. HttpApplication. LogRequest event occurs when ASP. NET has completed the event processing program. Public event EventHandler PostLogRequest; // Abstract: // a hosted object associated with the request has been released. Public event EventHandler RequestCompleted; // Summary: // retrieves the Request status associated with the current request (for example, session status. Public event EventHandler PostAcquireRequestState; // Summary: // ASP. NET occurs before it starts executing an event handler (for example, a page or XML Web Service. Public event EventHandler PreRequestHandlerExecute; // Summary: // occurs when an ASP. NET event handler (such as a page or XML Web Service) is executed. Public event EventHandler PostRequestHandlerExecute; // Summary: // ASP. NET occurs after all request event handlers are executed. This event causes the status module to save the current status data. Public event EventHandler ReleaseRequestState; // Summary: // This event occurs when ASP. NET has executed all request event handlers and the Request status for storing data. Public event EventHandler PostReleaseRequestState; // Summary: // when ASP.. NET to enable the cache module to store the events that occur when a response to a subsequent request from the cache is provided. Public event EventHandler UpdateRequestCache; // Summary: // This occurs when ASP. NET completes the updated cache module and stores the response for subsequent requests in the cache. Public event EventHandler PostUpdateRequestCache; // Summary: // ASP. NET occurs before any log records of the current request are executed. Public event EventHandler LogRequest; // Summary: // when ASP. NET obtains the current status associated with the current request (for example, session status ). Public event EventHandler AcquireRequestState. Public event EventHandler EndRequest; // Summary: // This event occurs when an unhandled exception is thrown. Public event EventHandler Error;
When we see the last event, when an unhandled exception occurs, it is the last line of defense. If exceptions are not captured using aop, Application _ Error is displayed.
In Global. asax, we can write this method
/// <Summary> /// you can handle global exceptions /// </summary> /// <param name = "sender"> </param> // <param name = "e"> </param> protected void Application_Error (object sender, eventArgs e) {// code var error = Server when an unprocessed error occurs. getLastError (); var code = (error is HttpException )? (Error as HttpException). GetHttpCode (): 500; // if it is not an HttpException, record the error message if (code! = 404) {// email or log error message} Response. write ("error"); Server. clearError (); string path = Request. path; Context. rewritePath (string. format ("~ /Errors/Http {0} ", code), false); IHttpHandler httpHandler = new MvcHttpHandler (); httpHandler. ProcessRequest (Context); Context. RewritePath (path, false );}
In this method, we can also get exception information, record logs or email notifications,
You can also jump to the error page based on the error code.
You can also add additional information on the current error page.
Very powerful.
If this method is not written, the default method encapsulated by the framework is used. This method is used when customError nodes are configured in web. config.
There may be more and better ways. Hope to provide guidance and I want to learn.
, I hope I can come back and see my step when my technology is successful.