Application-Level Event Handlers In ASP.Net

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.

Create an Asp.NET application-level event handler
  • If your Web site does not already have a Global.asax file, create one in the root of the site.
  • 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.
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.

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.
Tags: , ,
Hot on Web:


About author