How to: Create ASP.NET Application-Level Event Handlers

ASP.NET automatically binds application events to event-handler methods in the Global.asax file using a naming convention of Application_event, such as Application_BeginRequest and Application_Error. For more information, see ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0.

This code example handles the application-level Error event and writes error information to the system event log. The Error event is raised whenever an application error or unhandled page error occurs.

To create an Asp.NET application-level event handler

  1. If your Web site does not already have a Global.asax file, create one in the root of the site.

  2. Create an event-handler method whose name follows the pattern Application_event. For example, to handle an application Error event, create a handler named Application_Error that takes an Object parameter and an EventArgs parameter.

Example

The following code example shows a handler in the Global.asax file for the Error event. The handler in the example is called whenever an unhandled exception occurs anywhere in the application. If an exception is caught in a try/catch block or by a page object's Error event, the application does not raise the Error error.

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' check to see if the ASPNETApplication log exists
    If Not System.Diagnostics.EventLog. _
            SourceExists("ASPNETApplication") Then
        System.Diagnostics.EventLog. _ 
            CreateEventSource("ASPNETApplication", "Application")
    End If
    System.Diagnostics.EventLog. _
        WriteEntry("ASPNETApplication", 
        Server.GetLastError().Message)
End Sub
void Application_Error(Object sender, EventArgs e)
{
    if(!System.Diagnostics.EventLog.SourceExists
            ("ASPNETApplication"))
    {
        System.Diagnostics.EventLog.CreateEventSource
           ("ASPNETApplication", "Application");
    }
    System.Diagnostics.EventLog.WriteEntry
        ("ASPNETApplication", 
        Server.GetLastError().Message);
}

The code writes an entry to the system event log. It checks first to determine whether the event log entry named ASPNETApplication exists; if not, the code creates it. The code gets the error message associated with the error by calling the GetLastError method, and then writes the error message to the log.

Security

This code example requires that the application have permission to access the system event log. For more information about using the system event log, see How to: Write to an Application Event Log (Visual Basic).

See Also

Concepts

ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0

Other Resources

Error Handling in ASP.NET Pages and Applications