Sunday, January 13, 2013

The Global.asax File in ASP.NET

The Global.asax file allows you to write code that responds to global application events. These events fire at various points during the lifetime of a web application, including when the application domain is first created (when the first request is received for a page in your website folder). 

To add a Global.asax file to an application in Visual Studio, choose Website รค Add New Item, and select the Global Application Class file type. Then, click OK.

The Global.asax file looks similar to a normal .aspx file, except that it can’t contain any HTML or ASP.NET tags. Instead, it contains event handlers. For example, the following Global.asax file reacts to the Application.EndRequest event, which happens just before the page is sent to the user:

<%@ Application Language="C#" %>
<script language="c#" runat="server">
protected void Application_OnEndRequest()
Response.Write("<hr />This page was served at " +

This event handler uses the Write() method of the built-in Response object to write a footer at the bottom of the page with the date and time that the page was created

Each ASP.NET application can have one Global.asax file. Once you place it in the appropriate website directory, ASP.NET recognizes it and uses it automatically. For example, if you add the Global.asax file shown previously to a web application, every web page in that application will include a footer.

Application.EndRequest is only one of more than a dozen events you can respond to in your code. To create a different event handler, you simply need to create a subroutine with the defined name. 

Event-Handling Methods

Occurs when the application starts, which is the first time it receives a request from any user. It doesn’t occur on subsequent requests. This event is commonly used to create or cache some initial information that will be reused later.

Occurs when the application is shutting down, generally because the web server is being restarted. You can insert cleanup code here. 

Occurs with each request the application receives, just before the page code is executed.

Occurs with each request the application receives, just after the page code is executed.

Occurs whenever a new user request is received and a session is started. 

Occurs when a session times out or is programmatically ended. This event is only raised if you are using in-process session state storage (the InProc mode, not the StateServer or SQLServer modes).

Occurs in response to an unhandled error. 

No comments:
Write comments
Recommended Posts × +