Support for error handling in ASP. NET

Source: Internet
Author: User

ASP. NET has a good new feature: it provides rich support for handling and tracking runtime errors. In particular, it provides a very simple way for managers to ensure that errors in the frightening "ASP 43433ax" hexadecimal format will never be displayed to customers. On the contrary, it allows display of a relatively customized information, such as "sorry, this site is unavailable ". ASP. NET also provides a powerful method for developers to equip their code and provide management with additional information and notifications that occur on the work site. This article describes these two technologies in detail and includes a sample code at the end. You can use it to test it directly.
Ensure that security information is not leaked
ASP. NET is the same as ASP in the past. When a running time or compilation time error occurs on the server, an html error page is generated. Unlike ASP, ASP. NET is particularly concerned with ensuring that "security" information is not disclosed due to this error by default. Especially if you click a server from a remote machine. "Out of the box" error handling settings will not display remote machine compiler information, leakage of configuration information, file names, stack records, source code or linear data. On the contrary, remote users only see a common message such as "an application error occurs. To view the error details, you must: 1) Click the page again from the local server, or 2) in the config of the machine or application. modify the configuration settings in the web file to allow remote access:

<configuration>
<customerrors mode="off" />
</configuration>
We hope that by setting the default status as we have to be "secure", we can ultimately help protect application integrity and security. In addition, many ASP developers, especially ASP administrators, complain about the common issues ).
Custom error page
Although the public error message we send to the user is secure, that is, it does not threaten the secret of the application, but such information is not good-looking. Maybe you want users to never see such information. On the contrary, if an error occurs during request processing, you want to display your "custom error page ", display your own brand and specific error information.
It is easy to add custom error messages to ASP. NET applications. First, write your own web page, which can be any type of Files:. htm,. aspx,. asp, and so on. Modify the configuration information in the config. web file of the application to point it to the file.
For example, the following configuration information indicates that the browser should be redirected to the "ErrorPage. aspx" page in case of any unscheduled handling error:
<configuration>
<customerrors mode="remoteonly" defaultredirect="ErrorPage.aspx" />
</configuration>
<customerrors>
The defaultredirect attribute in the tag defines the "default" page to which the user will be redirected when an error occurs. Alternatively, you can redirect to another page to overwrite the default value based on the http code status of the response. For example, redirect to a special "file not found" error page, "illegal access" error page, or "server conflict" error page.
For example, the following configuration information overwrites three specific http status codes, and all other errors are returned to a default page:
<customerrors defaultredirect="http://anotherhost/error.aspx" mode="remoteonly">
<error statuscode="500" redirect="http:/anotherhost/pages/callsupport.html" />
<error statuscode="404" redirect="http:/anotherhost/pages/adminmessage.html" />
<error statuscode="403" redirect="http:/anotherhost/pages/noaccess.html" />
</customerrors>
One thing we have encountered on the custom error page is that although they are very useful for completed situations, they are very difficult to deal with during the development process. It is because you expect that there will be bugs in the development process, and when you find it, you really want to see the actual error information tracking. To solve this problem, the <customerrors> tag supports a "mode" attribute with three values:
"On": indicates that custom error pages are always sent;
"Off": indicates that you always see the original error message when no custom error page is sent );
"Remoteonly": indicates that the custom error page is sent only when the remote browser clicks the site, and the developer who clicks the site on the actual machine sees the detailed error information ).
Equip the application to help administrators track errors
Although displaying custom error messages to customers is a good thing, you may still want to make it easy for developers and administrators to discover an error on the site in real time, it also identifies the problem, url, and exception information.
To solve this problem, ASP. NET introduces a new "Application Layer" event that can be processed in the Global. asax file: "Application_Error ". In the process of processing a web request, this method is called when an unprocessed exception occurs. Developers can obtain special information about the request, such as the url of the page to be displayed, the query string variable, the user agent, and the cookie value, and the information of the actual exception object that encapsulates the error information. Then you can continue and run any logic that they want to track and notify administrators and developers of problems. This may include using System. diagnostic APIs writes information to the NET Event Log and uses System. web. util SMTP Email APIs sends an email to the Administrator and writes information to a database.
For example, the following Global. asax file demonstrates how to write error messages to a custom NT Event Log "MyCustomLog", including page URLs and exception stack records:
<%@ Import Namespace="System.Diagnostics" %>
<script language="VB" runat=server>
Sub Application_Error(Sender As Object, E as EventArgs)
'Obtain the URL of the Request
Dim PageUrl as String = Request.Path
'Obtain the Exception Object for the Error
Dim ErrorInfo as Exception = Server.GetLastError()
'Construct Error Message to Write to NT Event Log
Dim Message As String = "Url " & PageUrl
Message = Message & " Error: "
Message = Message & ErrorInfo.ToString
'NT Event Log Name to Write Message To
Dim LogName As String = "MyCustomLog"
'Create Event Log if It Doesn’t Exist
If (Not EventLog.SourceExists(LogName)) Then
EventLog.CreateEventSource(LogName, LogName)
End if
'Fire off to Event Log
Dim Log as New EventLog
Log.Source = LogName
Log.WriteEntry(Message, EventLogEntryType.Error)
End Sub
</script>
To see how everything actually works, try to create a new IIS application vroot on the machine, and then copy the sample code above to a new Global. in the asax file, this file is created in the application root directory. Then, copy/paste the following code snippet to the "Blowup. aspx" file:
<body>
<%
Dim x
x.BlowUp()
%>
</body>

Note: This file will always cause a running time error, because it causes an invalid reference exception, and the "x" object is not created at all, and there is no "Blowup" method. Therefore, when you click the page in a browser, an error message is displayed.
In addition to viewing the error message in the browser, because the Application_Error event exists in Global. asax, you will also see it in the NT Event Log. To view this, select "Start Menu> program> Management Tools> Event Viewer" and click "MyCustomLog" on the right side to display the log Content. Double-click a specific project to view the url of the page and the record details of the stack.
Note: NT Event Logs can be viewed remotely, so this is an easy way to track the machine status from a distance. Note: When you dynamically create a new NT Event Log, you must exit and restart the NT Event Viewer every time to see it displayed in the list.
Since we can easily track error details when a new ASP. NET application has internal problems, we need to ensure that all our customers see is customized error information. Create a "mermerror. aspx" page in vroot:
<body>
</body>
Modify the config. web file to point it to the page:
<configuration>
<customerrors mode="on" defaultredirect="CustomError.aspx"/>
</configuration>
Click the BlowUp. aspx page again to view the browser automatically redirected to the friendly error page. If you view the NT Event Log, you will see all the details necessary to notify an administrator about this error, as well as all the details necessary for developers to identify and fix it.
Note that because the customer information is stored in the config. web file instead of the IIS metadata, it can be installed through "xcopied" without requiring users to use the IIS Admin tool. This custom feature of ASP. NET also works In IIS4 and iis5.
(

Related Article

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.