Global. asax

Source: Internet
Author: User
Tags classic asp

Global. asax is a text file that provides globally available code. The Code includes the application's event handler and session events, methods, and static variables. This file is also called an application file.

Any code in the global. asax file is part of its application. Each application can have only one global. asax file under its root directory. However, this file is optional. If the global. asax file is not available, the application applies the default behavior provided by the HttpApplication class to all events.

Tip: the classic ASP has a file named global. asa in a similar format and structure as global. asax. In fact, if you copy a running global. asa file code to global. asax, the application can also run.

When the application is running, the contents of global. asax are compiled into a class inherited from the HttpApplication class. Therefore, all methods, classes, and objects in the HttpApplication class are available to applications.

CLR monitors changes in global. asax. If the file changes, a new application copy is automatically started and a new application domain is created. Requests currently being processed by the original application domain are allowed to end, and any new requests are handled by the new application domain. When the last request of the original application's procedural domain is processed, the application domain is cleared. This effectively ensures that the application can be restarted without being noticed by any user.

To prevent application users from viewing the source code by downloading the application, ASP. NET is configured by default to prevent users from viewing the contents of global. asax. If someone enters the following URL in a browser:

Http: // localhost/progaspnet/Global. asax

This will receive a 403 (forbidden access) error message or similar information, such:

This type of page is not served.

Tip: In simple terms, the web. config file is similar to global. asax. If the file is changed, the application will automatically "restart ". Similarly, it is impossible to view the web. config file in the browser.

The Global. asax file is similar in appearance and structure to the page file (. aspx. It can have one or more parts, which are briefly described as follows:

L command

L script block

L Object Declaration

Just as Web pages and Web services can use the code hiding function, global. asax can do the same. However, unlike Web pages and Web Services, VS2005 does not use the code hiding function for global. asax by default.

Tip: Visual Studio 2005 preview uses the code to hide the model for global. asax by default. Currently, code hiding is still supported, but it is not used by default.

To. asax uses the code hiding technology to use the Inherits attribute of the Application Command (similar to the Page command of the Page file, which will be detailed in the next section) located in the file header. This attribute points to global. asax. the Code hiding class in cs.

At the same time, there is also a CodeBehind attribute used to point to the code hidden file. However, if it points to a location other than the App_Code folder, you must manually edit the class file.

Right-click the website in Solution Explorer or click the website menu, and select "Add New Item... ", and then select the global application class, you can add a global for the Web application. asax file. Retain the default name global. asax.

VS2005 will create a file listed in example 18-1. The template contains blank declarations for the following five events: Application_Start, Application_End, Session_Start, Session_End, and Applica-tion_Error.

Example 18-1: global. asax Template

<% @ Application Language = "C #" %>

In the global. asax file listed in example 18-2, some values are set for the application status, and an entry is written to the log file each time the application starts. To use this example, you must ensure that the ASP. NET account has write permission to the root directory c: \ (not recommended in the product system ).

Example 18-2: global. asax example

<% @ Application Language = "C #" %>

Command

Compared with Web pages and Web Service files, global. asax can start with multiple commands. These commands specify the application compilation settings when processing ASP. NET files. Compared with the Page command, the Application command can

Accepts one or more attribute/value pairs with dictionary structures. Three commands are supported: Application, Import, and Assembly.

The Application Command sets the Application-specific attributes of the compiler. The following is an example of an Application command:

<% @ Application Language = "C #" Inherits = "WebServiceConsumer. Global"

Description = "A sample application" %>

The Language attribute can be set to any standard Language name: VB, C #, JS, or VJ #, which corresponds to VB2005, C #, JScript. NET, or J #. (You can use any third-party language that supports the. NET platform.) The default value is C #. The Language here sets the Language for the global. asax file, rather than other application code files. For example, you can use C # in the global. asax file and VB2005 in the. aspx file, and vice versa.

The Inherits attribute specifies the inherited class name, such as the class in the code hidden file.

The Description attribute accepts the text Description of the application, which is ignored by the analyzer and compiler.

The CodeBehind attribute is used in Visual Studio. NET (not VS2005) to specify included code hidden files.

The Import command only contains one Namespace attribute. The specified namespace is explicitly imported into the application so that all its classes and interfaces are available. The imported namespace can be part of the. NET Framework or a user-defined namespace.

The following is a typical Import command:

<% @ Import Namespace = "System. Data" %>

Only one Namespace attribute is allowed. To Import multiple namespaces, you must use multiple Import commands.

The following namespace is automatically imported to all Web applications, so there is no need to use the Import command.

L System

L System. Collections

L System. Collections. Specialized

L System. Configuration

L System. IO

L System. Text

L System. Text. RegularExpressions

L System. Web

L System. Web. Caching

L System. Web. Security

L System. Web. SessionState

L System. Web. UI

L System. Web. UI. HtmlControls

L System. Web. UI. WebControls

The Assembly command is used to link an Assembly to the current application during compilation. In this way, all Assembly classes and interfaces are available to applications.

Tip: The keystore is the .dllor .exe file, which will be explained in detail in the next chapter.

Since the Assembly is referenced during compilation, you can use the Assembly command to bind the Assembly and then load it into the application pool at runtime.

An assembly located in the application Assembly Cache (that is, the code file in the bin directory and App_Code directory) can be automatically connected to the application. Therefore, no Assembly in the bin directory or compiled by the code in the App_Code directory needs to be connected using the Assembly command.

The Assembly command has two attributes: Name and Src. The Name attribute is a string that indicates the Name of the Assembly connected to the application. It cannot contain a path. The Src attribute is the path pointing to the source file (only the relative path). These files will be dynamically compiled and connected.

Each assembly instruction can have only one attribute. To connect multiple assemblies, use multiple Assembly commands.

The Assembly command is similar:

<% @ Assembly %>

<% @ Assembly Src = "sources/SomeSourceFile. cs" %>

Script Block

A typical global. asax file contains a large amount of code, which is included in the script block starting and ending with the script Tag:

If you use code hiding, although the Code in the Code hiding file does not include a script tag, the Code contained in the Code hiding file is equivalent to the Code in the script block.

The code in the script block can contain the event handler or method, which will be described below.

Event

Just as web pages and controls can publish events, Application objects and Session objects in applications can also publish events. These events can be processed by event handlers in the global. asax file or specified file. For example, the Application_Start event is triggered when the application starts to run, and the Application_End event is triggered when the application ends. Some Application events are triggered when a page request is sent, while other events, such as Application_Error, are triggered only under specific circumstances.

The global. asax file code in example 18-2 illustrates the Application_Start and Application_End events. The Application_Start event in example 18-2 sets two Application attributes: A string named strConnectionString and a string array named arBooks. The event handler method calls an auxiliary method named WriteFile, which is included in the global. asax file. This auxiliary method writes a string to a log file. The WriteFile method code in example 18-2 is as follows:

Void WriteFile (string strText)

{

System. IO. StreamWriter writer =

New System. IO. StreamWriter (@ "C: \ test.txt", true );

String str;

Str = DateTime. Now. ToString () + "" + strText;

Writer. WriteLine (str );

Writer. Close ();

}

WriteFile is a simple method for logging. This method initializes a StreamWriter object based on text files and hard-coded c: \ test.txt. It adds a timestamp to the file and writes the string passed through the method. The Boolean parameter of the StreamWriter method is true, indicating that if the file already exists, the text line is appended to the file. If the file does not exist, create a file.

The Application_End event processing method calls another WriteFile method. It adds a log entry to record the end of the application.

To view the results of these two event handlers, you can make some meaningless edits to global. asax and save the files. The application is forcibly terminated. Request any URL address in the virtual directory. For example, you can use a web page in the previous chapter-either actually one-or a self-created web page. Sample 18-3 shows the log file content.

Example 18-3: Test.txt excerpt

8/26/2006 5:46:23 Application Starting

8 /26/2006 6:13:35 Application Ending

8/27/2006 10:17:39 Application Starting

10:18:23 Application Ending

8/27/2006 10:18:36 Application Starting

Like the Start and End events of the Application object, the Session object also has Session _ Start and Session_End events. This allows the application to run code for each session each time it starts and ends.

As shown in the highlighted method name in example 18-4, it includes all possible application event handlers in the global. asax file. You can easily view the application lifecycle when page requests are accepted, processed, and presented.

Example 18-4: Global. asax Event Description

<% @ Application Language = "C #" %>

The following lists all events triggered by page requests in the order of triggering:

Application_BeginRequest

Triggered when ASP. NET starts processing each request. The code in the event processing will be executed on the page or before the service processes the request.

Application_AuthenticateRequest

Triggered before the verification request. (As described in Chapter 12th, verification is the process of confirming that the user is the person he said) allow the implementation of custom security pipelines in the event handler code.

Application_AuthorizeRequest

Triggered before authorization. (Authorization is the process of determining whether to request the user to have the permission to access resources.

This section describes how to implement custom security pipelines in the event handler code.

Application_ResolveRequestCache

ASP. NET determines whether a new output should be generated or triggered before the cache is filled. In any case, the code in the event handler will be executed.

Application_AcquireRequestState

Run the command before obtaining the session status.

Application_PreRequestHandlerExecute

Triggered before sending a request to a processing object serving the request. When an event is triggered, the HTTP handler processes the request.

Application_PostRequestHandlerExecute

Triggered when the HTTP processing program and page request are completed together. At this time, the Response object will get the data returned by the client.

Application_ReleaseRequestState

Triggered when an attempt is released or updated.

Application_UpdateRequestCache

If the output is cached, It is triggered when the cache is updated.

Application_EndRequest

It is executed when the request ends.

Application_PreSendRequestHeaders

Triggered before sending an HTTP header to the client. If response caching is enabled, no data is sent until all data is ready (the default condition. This event is always after the Application_EndRequest event. If response caching is disabled, this event is triggered whenever data is sent to the client. Response Control is controlled by an attribute of the Page command or WebMethod attribute of the Web service.

Application_PreSendRequestContent

Triggered before sending HTTP content to the client. Like the Application_PreSendRequestHeaders event, whether the Application_PreSendRequestContent event is triggered depends on whether the response cache is available.

The following lists application events that are triggered under specific conditions:

Application_Start

Triggered when the application starts. When you request any page in the application virtual directory for the first time, the application is started. If the application is already running, this event is not triggered.

Application_End

Triggered when the application ends. The configuration files (global. asax, global. asax. cs,

Global. asax. vb or web. config), or the server crashes or restarts, the application will end. Code that usually executes the clear function in the event handler, such as closing the database connection.

Session_Start

Triggered when each session starts. This is where the specific session code is placed.

Session_End

Triggered when the session ends. It provides an opportunity to store any data stored in sessions.

Application_Disposed

Triggered when CLR removes an application from memory.

Application_Error

An unprocessed error is triggered no matter when or where it occurs in the application. It provides a good opportunity to handle common application errors.

You can use the try... catch Block to handle specific errors in the Code, or use the ErrorPage attribute of the Page command to capture Page-level errors. Using these methods to handle any errors will not trigger the Application_Error event.

To test the new global. asax version, create a web page in example 18-5. View the GlobalEvents site. When the webpage is running, the page shown in 18-4 is displayed.

Example 18-5: default. aspx of the GlobalEvents website

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs"

Inherits = "_ Default" %>

Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd>

Global Events

Text = "End Session"

OnClick = "btnEndSession_Click"/>

Text = "Generate Error"

OnClick = "btnError_Click"/>

Figure 18-4: GlobalEvents

As shown in Figure 18-4, a series of application events are triggered. During the execution of these events, the. aspx page itself is displayed, followed by some other application events.

Warning GlobalEvents can run properly only in a real IIS virtual path.

The Session_Start event is triggered when the page is displayed for the first time, but it is not triggered in subsequent display. This is because the request is the same session. Click the "End Session" button to call the Session. Abandon method, which ends the current Session. The Session_Start event is triggered again when the next page is submitted to the server.

The Post button provides a simple method to submit the page again.

In Example 18-4, most application event handlers use the Response. Write method to display the triggered event. However, the Application_Start and Application_End Methods call the WriteFile method. If you try to use the Response. Write method in the event processing process

Display. Because the page session used for rendering is not running yet. However, when you check the log file c: \ test.txt, you will see the entries displayed when the application starts and ends.

The global. asax file shown in example 18-4 illustrates a method for using the Application_Error event. The Code is as follows:

Protected void Application_Error (Object sender, EventArgs e)

{

String strError;

StrError = Server. GetLastError (). ToString ();

If (Context! = Null)

Context. ClearError ();

Response. Write ("Application_Error" +"

");

Response. Write ("Error Msg:" + strError +"

"+

"End Error Msg

");

}

The event handler uses the GetLastError method of the HttpServerUtility object to report the final error. This error is converted to a string and assigned to a string variable:

StrError = Server. GetLastError (). ToString ()

Next, call the ClearError method of the HttpContext object to clear all the errors in the current HTTP request:

Context. ClearError ()

If the error is not cleared, the error will be displayed in the client browser, and the display result of the Respons-e. Write method still cannot be seen.

Finally, the Response. Write method displays a message, and the current error is displayed on the client.

Another way to report errors to users is to display the custom error handling page. To do this, use the following code line to replace the Response. Write method in the Application_Error event handler:

Response. Redirect ("CustomErrorPage. aspx? Msg = "+

Server. UrlEncode (strError ));

The preceding code line calls the UrlEncode method of the HttpServerUtility object and passes the error message as a QueryString parameter to the custom error handling code on the CustomErrorPage. aspx page. The CustomErrorPage. aspx page has a Label control named lblMessage. The following is the Page_Load method code on the page:

Void Page_Load (Object Source, EventArgs E)

{

LblMessage. Text = Request. QueryString ["Msg"];

}

The Generate Error button in Default. aspx triggers an Error to view the Error handling result. The code for clicking the event handler for this button is as follows, it will remove Zero exceptions:

Protected void btnError_Click (object sender, EventArgs e)

{

Int a = 5;

Int B = 0;

Int c;

C = a/B;

}

The server includes

The use of server-side includes the ability to include external source code files in applications. Before compilation, the code in the included files will be added to the global. asax file. Although the language of the application may be different from the language that includes files, the language used to include files must match the language used by the global. asax file.

The following is the syntax for the server:

In this syntax, the PathType type can be one of the 18-1 tables.

Table 18-1 PathType attributes

 

Path type

 

Description

 

File

 

The file name is the relative path of the directory containing the global. asax file.

 

Virtual

 

The file name is a virtual path that contains the website virtual directory.

View the global. asax file shown in example 18-4 and add the following code to the second line:

Create a new text file named IncludeFile. cs and store the file and global. asax in the same directory. This file requires the same script tag as the global. asax file.

Copy the WriteFile method on the global. asax page to include files, and then comment (or delete) The WriteFile method on the global. asax page. This file should be similar to the example 18-6.

Example 18-6: global. asax with files included

If you run any web page, it will not be different from the previous one, because all you do is to transfer the code in one file to another file.

If the CLR monitors changes to the global. asax file and, like restarting an application, the CLR also monitors changes to include files. If the included files change, the application will restart.

It is useful to include files for the same standard code included in multiple applications. These common codes may include database access methods, write log records, error handling pipelines, logon, or basic type code snippets for each application.

Object Declaration

Another way to include code in the global. asax file is to declare the object tag. These declared static objects are either Application or Session objects. This can be used in an application or each session.

There is another one below. If you are interested, you can check it out.

Http://www.cnblogs.com/top5/archive/2009/10/16/1584337.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.