In the Global.asax file, we write code the same way we write in the code-behind file of a web form with a .aspx file. However, the main difference between these two types of files is that we cannot use any HTML or ASP.NET elements in the Global.asax file. Instead, this file contains predefined methods with certain names.
The Global.asax file defines various predefined methods for a class named Application. This class inherits from a base class named HttpApplication. Therefore, our application class is capable of directly accessing all the public and protected members of the HttpApplication class.
The Global.asax file is optional, but we cannot include more than one Global.asax file in any web application. Additionally, this file must always exist in the root directory of our web application project.
It is important to note that the Application Level Event Handlers in the Global.asax files are not attached to events in the same way as events triggered by other controls. Various Application Level Event Handlers need to be specified as a certain Protected Method Signature.
For example, when we want to complete an Application Level Task, we define the Event Handler that will execute in response to this event as a Protected Method named Application_OnEndRequest(). This method is automatically invoked when the HttpApplication.EndRequest event is triggered, which occurs when the Application Request initiated by the User is completed.
When our Web Application is loaded for the first time in the Application Domain, ASP.NET creates a pool of Application Objects and uses each object to complete a Request. This Pool System and the number of available Threads determine the number of instances, which can be between 1 and 100. Access to one of these various objects in the Request Pool is granted, and when the Request ends, the Object is reused for other Requests.
As the different Stages of our Web Application's Life Cycle are processed, ASP.NET calls the Trigger Method for the corresponding Event, and the associated Event Handler is executed in response.
Since the signature of each Application Level Event Handler in this Global.asax file is related to a specific event, if the signature of the specified event handler is not accurate, then the event handler code will not execute when its associated event is triggered but will be ignored by the ASP.NET Framework.
Therefore, generally, when we add the Global.asax file to our web application, empty methods related to various most commonly used Application Level Event Handlers are automatically created.
The Global.asax file that uses the Global Application Class must always be stateless. This is because application objects are reused for different requests.
So if we set the value of any value in one request, then that value can appear in the next request as well, and there is no way to know in which request this value will appear, because these application objects are dynamically reused by different requests.
Therefore, it is better not to declare any normal member variable in this class, unless the variable is not static, because the value of a static member remains the same for all application objects.
Application Events
We can handle two types of events in the Global.asax File:
Events that are triggered on each request. These include request-related and response-related events.
Events that are triggered only under certain specific conditions.
Although we have already seen various application-level events, the required application events are primarily in the following order:
Application_BeginRequest()
Application_AuthenticateRequest()
Application_AuthorizeRequest()
Application_ResolveRequestCache()
Application_AcquireRequestState()
Application_PreRequestHandlerExecute()
Application_PostRequestHandlerExecute()
Application_ReleaseRequestState()
Application_UpdateRequestCache()
Application_EndRequest()
We can represent the various events triggered during the execution of these event handlers as shown in the following diagram:
These are the events that are triggered on every request, whereas the event handlers that fire under some special conditions are as follows:
Application_Start()
Session_Start()
Application_Error()
Session_End()
Application_End()
Application_Dispose()
Application-level events are generally used for the initialization, cleanup, usage logging, profiling or troubleshooting of our application. However, it is not necessary to add this Global.asax file to specify these application-level events in every web application. Most applications can run normally without adding this file.
To use the global.asax file, you create a new file named global.asax in the root directory of your ASP.NET application. Then, you can define event handlers and application-level code in the Global class, which is a predefined class that represents the global.asax file.
Here is an example of how to handle the Application_Start event in the global.asax file:
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startupRegisterCustomRoutes();
ConfigureApplicationSettings();
}
</script>
In this example, the Application_Start event handler registers custom routes and configures application-wide settings when the application starts.
How to use global.asax file to customize the applications' behavior?
1. Application Initialization:
The Application_Start event in the global.asax file is triggered when the application starts. You can use it to perform application-level initialization tasks such as registering custom routes, configuring application-wide settings, or initializing global objects. Here is an example:
protected void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startupRegisterRoutes(RouteTable.Routes);
ConfigureApplicationSettings();
}
In this example, the Application_Start event handler registers custom routes using RouteTable.Routes collection and configures application-wide settings.
2. Session Management:
The Session_Start and Session_End events in the global.asax file are triggered when a user starts or ends a session. You can use them to perform session-level initialization and cleanup tasks, respectively, such as storing session-specific data, initializing user-specific settings, or tracking user activity. Here is an example:
protected void Session_Start(object sender, EventArgs e)
{
// Code that runs on session start
Session["UserId"] = GetUserIdFromDatabase();
}
In this example, the Session_Start event handler retrieves the user ID from the database and stores it in the Session object.
3. Error Handling:
The Application_Error event in the global.asax file is triggered when an unhandled error occurs in the application. You can use it to implement custom error-handling logic, such as redirecting to a custom error page or logging error information. Here is an example:
protected void Application_Error(object sender, EventArgs e)
{
// Code that runs on unhandled errors
Exception ex = Server.GetLastError();
LogError(ex);
Response.Redirect("~/Error.aspx");
}
In this example, the Application_Error event handler logs the error information using a custom LogError method and redirects to a custom error page.
4. Request Processing:
The Application_BeginRequest and Application_EndRequest events are in the global.asax files are triggered when a request begins or ends. You can use them to modify the behavior of incoming requests and outgoing responses, such as enforcing security policies, compressing response content, or adding custom headers. Here is an example:
protected void Application_BeginRequest(object sender, EventArgs e)
{
// Code that runs on incoming requestsif (Request.Url.AbsolutePath.Contains("Admin"))
{
if (Session["UserId"] == null || !IsUserAdmin(Session["UserId"].ToString()))
{
Response.Redirect("~/Login.aspx");
}
}
}
In this example, the Application_BeginRequest event handler checks if the requested URL contains the "Admin" keyword and if the user is authenticated and has admin privileges. If not, it redirects the user to the login page.
Steps:
Open your ASP.NET project in Visual Studio.
Add a new global.asax file to the project by right-clicking on the project in Solution Explorer, selecting "Add," and then selecting "Global Application Class" from the "Web" tab.
In the global.asax file, define event handlers and application-level code for the desired scenarios, such as Application_Start, Session_Start, Application_Error, and Application_BeginRequest.
Build and run the project to test the customized application behavior.
Conclusion
The global.asax file is a tool that allows you to customize the behavior of an ASP.NET application by handling application-level events and defining application-level code. By using the global.asax file, you can implement custom initialization and cleanup logic, error handling, and request processing logic to make your application more robust and flexible.
Commentaires