Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET global.asax usage

Tags:

asp.net

When to use and not to use global.asax file in asp.net application? I heard that you should use that file only at a pinch.

like image 702
Azat Avatar asked May 12 '10 08:05

Azat


People also ask

What is the use of global ASAX file in MVC?

The Global. asax file is a special file that contains event handlers for ASP.NET application lifecycle events. The route table is created during the Application Start event. The file in Listing 1 contains the default Global.

Is global ASAX mandatory?

asax is not required by ASP.NET for a website to run. It is, however, very useful for application-level functionality (like unhandled exception logging).

Can we have more than one global ASAX file in application?

You cannot have multiple Global. asax, unless you convert folders to Areas which is probebly overkill.


1 Answers

The Global.asax file is used to implement application and session level events, such as:

Application_Init - fired when an application first initializes

Application_Start - fired when the application first starts

Application_End - the final event fired when the application ends or times out

Session_Start - fired the first time a user’s session is started

Application_BeginRequest - fired with each new request

Application_EndRequest - fired when the application ends

Application_AuthenticateRequest - the event indicates that a request is ready to be authenticated.

Application_Error - fired when an unhandled error occurs within the application

Session_End - fired whenever a single user Session ends or times out.

Implementing these handlers can all be legitimate uses of the global.asax. For example, the Application_Error event handler typically logs any global errors, and the Application_End event handler typically contains application cleanup logic. These are good uses of the Global.asax. Use them whenever necessary, and don't be afraid if the file grows.

However, I have seen cases where developers have added all sorts of global methods to the global.asax that are indeed un-justified. For example, keep business logic related to a particular domain object inside the object itself rather than in the global.asax. If you find methods in the Global.asax that shouldn't be there refactor the work into the right location.

like image 116
Joe Ratzer Avatar answered Nov 25 '22 20:11

Joe Ratzer