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 " +
DateTime.Now.ToString());
}
</script>

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

Application_Start() 
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.

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

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

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

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

Session_End() 
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).

Application_Error() 
Occurs in response to an unhandled error. 

No comments:
Write comments
Recommended Posts × +