Application-Wide Logic

All code contained in the page class is scoped to the page. In other words, it is only visible to other code within that page class. This is true for variables and members such as methods, properties, and events. For most code, this is the appropriate behavior. However, there are often situations where it is either convenient or necessary to have code scoped more globally. For example, you may have a common method used in several pages. Though you can replicate the code on all the pages, it is far better to have a single source. Another example would be an application where a variable—a TrackingID, for example—is needed by every page as the user moves from page to page.

It is possible to scope your code application-wide (rather than per page). There are two ways of doing this: using the HttpApplication object and using the global.asax file.

HttpApplication Object

Just as a web page instantiates the Page class, when an application runs, it instantiates an object from the HttpApplication class. This object has methods, properties, and events available to all the objects within the application. It provides several objects that allow you to interact with the HTTP request:

  • The Application object for using application state

  • The Request object for getting access to the incoming request

  • The Response object for sending an HttpResponse back to the client

  • The Session object for access to session state

ASP.NET maintains a pool of HttpApplication instances during the lifetime ...

Get Programming ASP.NET, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.