When developing a Web site with ASP. WebForm, you need to customize the 404 error page. That's the way it is.
Set up a 404.html error page in the root directory of the Web site, and then add the following code to the Global.asax file:
<%@ Application Language="C#" %>
<script runat="server"> void Application_Error(object sender, EventArgs e)
{
Response.StatusCode = 404;
Server.Transfer("/404.html");
Server.ClearError();
} </script>
Then run the site, such as a random input 111.aspx, found on Chrome will automatically redirect to this 404.html, but on IE, but not.
To find the reasons on the Internet, find the following answers:
Sure enough, after adding some content to this page, the problem is solved.
In addition, this setting of the 404 error page, there is another problem is that when you enter the URL in the non-existent such as 111.aspx, it will automatically go to the custom 404.html
But when you enter a nonexistent 111 in the URL, without the suffix aspx, it doesn't show the custom 404.html.
Why does this happen? How should we solve it?
WORKAROUND: You need to configure in Web. config to include the following statement in the <system.webServer> configuration node
<httpErrors errorMode="Custom" existingResponse="Replace">
<clear />
<error statusCode="404" path="404.html" />
</httpErrors>
Detailed processing of the ASP.NET website custom error page method, you can refer to the following article, written very well
Reprinted from http://edi.wang/post/2014/1/11/iis7-aspnet-custom-error-best-practice
-------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ------------------- Summary of error page and exception log for ASP.NET website above IIS7
Custom error pages and exception records are a very old topic, but they can still make people pop up to the present. After I have done countless trials and summed up the experience and principles, I wrote this article and I am already a policeman.
Scope and limitations of this article
This article only applies to ASP.NET 4.0 integrated mode applications deployed in IIS7 or above. IIS7 or above means Windows Server 2008 and above. I have tested it on WS2012R2, IIS8.
The methods in this article apply to both ASP.NET WebForm and MVC applications.
The problem addressed in this article
Is the static error page good or the dynamic error page good? How can I design ASP.NET website error handling?
I don't want the error page to be followed by the small tail of aspxerrorpath=....
My custom error page is good for debugging in VS. Why can't I deploy it to the server?
My custom error page can display normally, but why is the returned Http status code incorrect?
How to record the exception log, is there a better practice?
First, the choice of the error page
Is it better to choose a static html page as the error page, or use .aspx or MVC View to display the error page? Many people have different preferences for this problem. I strongly recommend that you use the html static page as the error page. Please see the analysis:
First of all, people who use dynamic pages are only trying to solve three problems: display error summary, record log, and return the correct status code. However, the biggest problem with dynamic pages is that they are themselves processed by ASP.NET and background code. If your background code is exploding, or ASP.NET is exploding, then your error page is requested, It will trigger another error in itself. Static html is not going to have this problem. As for the practice of building an ErrorController in MVC, it is even more undesirable. MVC is based on ASP.NET. MVC's Controller can only catch MVC's own errors, and can't catch ASP.NET errors. That is to say, when your error is not on the MVC level, ErrorController has no use. The land of martial arts. For example, when the MVC application you are deploying lacks the MVC dll, the MVC framework itself will not run. How can this error be caught?
In addition, I think that on an Internet site, you should never show any error summary to visitors. This is very unsafe. So there is no need to use dynamic pages at all.
The problem with returning the correct status code is this: Many small partners find that their error page can be displayed, but the returned status code is 200 OK, so use the dynamic page and write the code with Response.StatusCode = 500. Strong. This has a solution in a later article, so don't risk using dynamic pages for status codes. Some small partners will ask, what is the risk that I can only write a Response.StatusCode=500? Oh, think about this situation: 404.cshtml, razor engine dll is gone...
In addition, one principle is that the error page should be independent. If your static page uses external resources such as images and CSS, it is recommended to embed it in the page to make a single file, so as not to ask the relevant resources to raise an exception again when the error page is displayed. The little friend has to ask again, ask for a CSS and a picture of what, swollen what will cause an exception? Then look at this: resources.axd?image=..., huh, huh.
So after using a static page, what should I do with logging? The correct approach should be to the "Application_Error" event handler in Global.asax. There will be a solution later.
Second, the configuration error page: customErrors VS httpErrors
First, there are two ways to display the error page. If you open IIS, you will see two places with error pages: .NET Error Pages and Error Pages.
From a developer's perspective, the ".NET Error Pages" under ASP.NET Section is the web.confg/system.web/customErrors node. The "Error Pages" under IIS Section is the web.config/system.webServer/httpErrors node, which is unique to IIS7 and above.
Any changes to both of these on IIS are actually modifying the web.config file.
So which one should we use to configure a custom error page? One of my principles is to let IIS show the error page to the user instead of relying on ASP.NET. The reasons are as follows:
The problem with CustomError:
a) By default, CustomError will use 302 redirect to display the error page. If the client requests a 404 page, it will get a 302 followed by a 200OK. For humans, this is OK, after all, the user sees a friendly error page, but the search engine will think that the non-existent address is a normal page and put your 404 page into the search results. And each time an error is raised, the URL will be followed by the small tail of aspxerrorpath, for example:
Http://yoursite.com/404.html?aspxerrorpath=/somethingnotexsit
b) After configuring redirectMode=“ResponseRewrite”, it will cause a problem. In 2009, someone submitted a bug to MS Connect, but Microsoft does not intend to fix this bug. That is, the mode is valid on the ASP.NET Development Server that comes with VS. The browser displays the parsed HTML page. After deploying to IIS, the browser displays raw html, which is the HTML of your error page. Code. And the behavior is not certain, and God knows what happens to your website's environment deployment.
c) The speciality of IIS7 and above: In integrated mode, IIS error page will take precedence over ASP.NET error page, that is, IIS default error page will overwrite your configured CustomErrors page, which is why you debug under VS Ok, it’s blasting when deployed to the server.
After IIS7, depending on your configuration, user requests are not necessarily processed on the ASP.NET pipeline. If the place where the exception is thrown is not in ASP.NET, the error page for CustomErrors will not be displayed.
Therefore, I strongly recommend that you use the httpErrors node instead of CustomErrors to configure the error page.
Third, File or ExecuteURL: the correct allocation of httpErrors
First paste a correct configuration example: it is configured with File.
Pay attention to two places:
The slash is the backslash "\" of the Windows file path instead of the slash "/" of the URL URL
Path does not start with "~" or "\"
Don't ask me why, I don't know, it's good to do it anyway.
If you unfortunately use ExecuteURL, you will find that the URL path can only start with "/":
And your error page will return 200OK instead of the correct 404, 500 and other error codes. This was written in my previous article:
http://diaosbook.com/Post/2012/6/24/correct-way-to-implement-custom-error-page-return-statecode-instead-of-http-200
The use of File means that when the error is revealed, IIS will paste the contents of the target File, such as 404.html, into the current Response stream, keeping the Http status code still 404. This is what we want.
Fourth, abnormal log records
The article raised a question at the beginning, there is a dynamic page, how to record the error log? My approach is to deal with it in Global.asax.
The Application_Error event sample code is as follows:
var exception = HttpContext.Current.Server.GetLastError();
if (null != exception)
{
// by default 500
var statusCode = (int)HttpStatusCode.InternalServerError;
if (exception is HttpException)
{
statusCode = new HttpException(null, exception).GetHttpCode();
}
else if (exception is UnauthorizedAccessException)
{
// to prevent login prompt in IIS
// which will appear when returning 401.
statusCode = (int)HttpStatusCode.Forbidden;
}
if ((LogHttpNotFound && statusCode == 404) || statusCode != 404)
{
if (null != _loggerFunc)
{
LoggerFunc(string.Format("ASP.NET Error Captured, Request URL: {0}, Exception:",
HttpContext.Current.Request.Url), exception);
}
}
ExceptionInfo = exception.Message;
_statusCode = statusCode;
}
A small suggestion is not to record 404 errors, because your website will be smashed by various search engines, scanning tools and hackers on the Internet. One way to attack is to guess the directory through the dictionary, and return 404 is non-existent, return 403 is there. So, when you encounter such a boring hacker, if you record a 404 request, your log will be very large...
The component I use for logging is NLog, which is simple to configure and easy to use. Log4net has not been updated for a long time.
If you decide to design your own log module, there are two principles to keep in mind:
The log module itself cannot affect the entire system because it bursts itself, that is, any exceptions in the log module should not bubble outward.
Considering the situation of concurrently writing logs, the log operation should be Fire and Forget, and the application should not wait for the log to be written.
V. Summary
Use a static html page as the error page.
Use httpErrors to configure the error page, the purpose is to be compatible with IIS7 and above environment, return the correct error code, remove the aspxerrorpath small tail.
Log records are written in Global.asax and recorded in the Application_Error event
Set 404 custom error page in ASP.NET website