Original: http://www.cnblogs.com/dudu/p/aspnet_custom_error.html
To handle custom errors in ASP. Errors First, discard the use of web.config\customerrors.
<customerrors mode= "RemoteOnly" defaultredirect= "/error/error.htm" > <error statuscode= "404" redirect= "/error/404.htm"/></customerrors>
One of the biggest drawbacks of using web.config\customerrors is that it redirects when the custom error page is displayed:
Http://www.cnblogs.com/error/error.htm?aspxerrorpath=/cmt/p/3789549.html
This can lead to 2 of problems:
1. The redirected URL is provided when the user is given a feedback question.
2. Users will not be able to retry by refreshing the browser, or after the problem is resolved by refreshing the browser to return to normal.
The best treatment we think of at the moment is in the Global.asax.cs Application_Error.
The code is as follows:
protected void Application_Error (Object sender, EventArgs e) { Exception LastError = Server.GetLastError (); if (LastError! = null) { if (LastError is HttpException) { if (((HttpException) lasterror). ErrorCode = = 404) { response.statuscode = 404; Server.ClearError (); return; } } CNBlogs.Infrastructure.Logging.Logger.Default.Error ("Application_Error", LastError); Response.statuscode = $; Server.ClearError (); }}
Since we have specified a 404/500 wrong custom error page in IIS, we only need to return the status code (requires more than IIS 7.0).
After this processing, it is also convenient to log the log4net logs before the custom errors are displayed.
Also note that it is important to server.clearerror (), otherwise ASP will continue processing according to Web.config\customerrors (the custom error handling in the code will be invalidated), The error message is also logged to the Windows log (since we have logged the Log4net log, there is no need to log the Windows logs again).
You may ask, a few lines of code can solve such a simple problem, it is worth selectmen write a blog to send on the homepage?
Value! Because we didn't take this place seriously, we paid a price for it many times. Maybe there are people in the garden who are not paying attention to the problem in this place.
Step on their own pits, write their own blog, and then let others no pit can tread, I think this is also a blog to write a value embodiment of it.