Azat
Azat

Reputation: 2335

ASP.NET global.asax usage

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.

Upvotes: 6

Views: 3994

Answers (3)

Joe Ratzer
Joe Ratzer

Reputation: 18549

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.

Upvotes: 6

awe
awe

Reputation: 22442

If you need something special to happen on Application start/end or Session start/end, or globally handle exceptions you could use it to map the events in the Apllication and Session life cycles.

Upvotes: 0

Midhat
Midhat

Reputation: 17810

global.asax is a HTTPModule. All requests go through the global.asax and other modules before they reach your page handlers. Use this to perform certain tasks on your request or response, like url routing, global error handlign etc.

Upvotes: 1

Related Questions