Programming Microsoft ASP.NET 4 - Dino Esposito [333]
Compiling global.asax
When the application is started, global.asax, if present, is parsed into a source class and compiled. The resultant assembly is created in the temporary directory just as any other dynamically generated assembly would be. The following listing shows the skeleton of the C# code that ASP.NET generates for any global.asax file:
namespace ASP
{
public class global_asax : System.Web.HttpApplication
{
//
// The source code of the "global.asax" file is flushed
// here verbatim. For this reason, the following code
// in global.asax would generate a compile error.
// int i;
// i = 2; // can't have statements outside methods
//
}
}
The class is named ASP.global_asax and is derived from the HttpApplication base class. In most cases, you deploy global.asax as a separate text file; however, you can also write it as a class and compile it either in a separate assembly or within your project’s assembly. The class source code must follow the outline shown earlier and, above all, must derive from HttpApplication. The assembly with the compiled version of global.asax must be deployed in the application’s Bin subdirectory.
Note, though, that even if you isolate the logic of the global.asax file in a precompiled assembly, you still need to have a (codeless) global.asax file that refers to the assembly, as shown in the following code:
<%@ Application Inherits="MyApp.Global" %>
You’ll learn more about the syntax of global.asax in the next section, “Syntax of global.asax.” With a precompiled global application file, you certainly don’t risk exposing your source code over the Web to malicious attacks. However, even if you leave it as source code, you’re somewhat safe.
The global.asax file, in fact, is configured so that any direct URL request for it is automatically rejected by Internet Information Services (IIS). In this way, external users cannot download or view the code it contains. The trick that enables this behavior is the following line of code, excerpted from machine.config:
ASP.NET registers with IIS to handle .asax resources, but then it processes those direct requests through the HttpForbiddenHandler HTTP handler. As a result, when a browser requests an .asax resource, an error message is displayed on the page, as shown in Figure 16-1.
Figure 16-1. Direct access to forbidden resources, such as *.asax files, results in a server error.
When the global.asax file of a running application is modified, the ASP.NET runtime detects the change and prepares to shut down and restart the application. It waits until all pending requests are completed and then fires the Application_End event. When the next request from a browser arrives, ASP.NET reparses and recompiles the global.asax file, and again raises the Application_Start event.
Syntax of global.asax
A few elements determine the syntax of the global.asax file. They are application directives, code declaration blocks, server-side