Today we learn about use of Global.asax in asp.net application, why and how to write code in Global.asax is Global.asax necessary in application!
What is Global.asax ?
Global.asax is also known as Application File in ASP.NET, the file is used to handle application level and session level events, so if we need any particular task to be carried out in any of those events, we can write code there as per need.
Global.asax contains a Class that is inherited from System.Web.HttpApplication class which has all events for application lifecycle.
Here is the class associated with Global.asax file.
public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterOpenAuth(); RouteConfig.RegisterRoutes(RouteTable.Routes); } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs Exception ex= Server.GetLastError(); } void Application_BeginRequest(object sender, EventArgs e) { } void Application_EndRequest(object sender, EventArgs e) { } }
As you can see in above code, for each event there is method where you can write code.
public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterOpenAuth(); RouteConfig.RegisterRoutes(RouteTable.Routes); } }
All type of config registration code are written inside Application_Start method, so if you have any other task to be carried out while starting the application, you can write there inside Application_Start event.
public class Global : HttpApplication { void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs Exception ex= Server.GetLastError(); } }
Similarly another very useful event is Application_Error, gets executed when any erro occurs in application, so using Server.GetLastError() you can get the last error details and capture them into your log files by writing some additional code.
Some of the events in global.asax fired for every request some are not, so let’s understand events
Global.asax Events gets fired for every request.
Best way to experiment all these events in your application is just create a simple asp.net web application and then add a Global.asax file in that, then write all above events in your global.asax.cs file, then put a break point on Application_BeginRequest, now run the application and click on some page to experiment all of them.