ASP. NET Global.asax Detailed

Source: Internet
Author: User
Tags script tag urlencode classic asp

Recently in the study of Bbsmax code, but always do not know where the entrance, and then on the various files analysis, and then finally in the Global.asax file to see Application_BeginRequest understand the entrance, so now to remedy this knowledge. The following documents are reproduced:

Document Source: http://club.topsage.com/thread-485397-1-1.html

Global.asax is a text file that provides globally available code. The code includes the application's event handlers, as well as session events, methods, and static variables. Sometimes the file is also called an application file.
Any code in the Global.asax file is part of the application in which it resides. Each application can have only one Global.asax file in its root directory. However, this file is optional. If there is no Global.asax file, the application applies the default behavior provided by the HttpApplication class to all events.
Tip: Classic ASP has a file named Global.asa similar to global.asax and constructed. In fact, if you copy a running Global.asa file code into Global.asax, the application can also run.
When the application runs, the contents of the Global.asax are compiled into a class that inherits from the HttpApplication class. Therefore, all methods, classes, and objects in the HttpApplication class are available to the application.
The CLR monitors the changes in the Global.asax. If it detects that the file has changed, it will automatically start a new copy of the application and create a new application domain. Requests that are currently being processed by the original application domain are allowed to end, and any new requests are processed by the new application domain. When the last request processing of the original application domain is completed, the application domain is cleared. This effectively ensures that the application can be restarted without being detected by any user.
To prevent application users from downloading the application, see the source code, ASP. NET is configured by default to prevent users from viewing Global.asax content. If someone enters the following URL in the browser:
Http://localhost/progaspnet/Global.asax
This will receive a 403 (Forbidden) error message or similar information such as:
This type of page was not served.
Tip: In simple terms, the Web. config file is somewhat similar to global.asax. If this file is changed, the application will automatically "reboot". Similarly, it is not possible to view the Web. config file in a browser.
The Global.asax file is similar in appearance and structure to a paging file (. aspx). It can have one or more parts, briefly described as follows:
L Instruction
L Script block
L Object Declaration
Just as Web pages and Web services can use the code-behind feature, Global.asax can do the same. However, unlike the conditions of Web pages and Web services, VS2005 does not use the code-behind feature for Global.asax by default.
Tip: Visual Studio 2005 preview uses the code-behind model for Global.asax by default. Code-behind is still supported, but not used by default.
In order to use the code-behind technique for Global.asax, you can use the Inherits property located at the head of the file with the application directive (similar to the page directive for the paging file, described in detail in the next section), which points to the code-behind class in Global.asax.cs.
At the same time, there is also a Codebehind property to point to the code-behind file. However, if it points to a location that is located outside the App_Code folder, you must manually edit the class file.
You can add a Global.asax file for your Web application by right-clicking the Web site in Solution Explorer or by clicking the Site menu, then selecting Add New Item ..., and then selecting the Global application class. Leave the default name global.asax.
VS2005 will create a file as listed in Example 18-1. The template includes a blank declaration for the following 5 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 that is enumerated in example 18-2, some values are set for the application state, and an entry is written to the log file each time the application starts. In order to use this example, you need to ensure that the ASP. NET account has write permissions to the root directory \ c (not recommended in the product system).
Example 18-2:global.asax Example
<%@ application language= "C #"%>
Instructions
Global.asax can start with multiple directives as compared to Web pages and Web service files. These directives specify the settings that the application compiles when processing the ASP. Compared to the page directive, the application directive can be
Accepts one or more attribute/value pairs that have a dictionary structure. Three instructions are supported here: application, import, and assembly.
The application Application directive sets the application-specific properties of the compiler. The following is an example of a application instruction:
<%@ application language= "C #" inherits= "Webserviceconsumer.global"
description= "A sample Application"%>
The Language property can be set to any of the standard language names: VB, C #, JS, or vj#, which correspond to VB2005, C #, JScript.NET, or J # respectively. (You can use any kind of support.) NET platform (third-party language) is the default value of C #. The language settings here are language-specific for Global.asax files, not other application code files. For example, you can use C # in a Global.asax file completely and legally, use VB2005 in an. aspx file, and vice versa.
The Inherits property specifies the inherited class name, which is representative of the class in the code-behind file.
The Description property accepts a textual description of the application, and the parser and compiler will ignore it.
The Codebehind property is in Visual Studio. NET (non-VS2005) to specify the included code-behind file.
The Import Import directive includes only one namespace property. The namespace you specify is explicitly imported into the application so that all of its classes and interfaces are available. The namespaces that are imported can be part of the. NET Framework or user-defined namespaces.
The following is a typical import directive:
<%@ Import namespace= "System.Data"%>
There can be only one namespace property. If you need to import multiple namespaces, you need to use multiple import directives.
The following namespaces are automatically imported into all Web applications, so it is not necessary to use the import directive.
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 Assembly directive is used to link an assembly to the current application during compilation. This enables the classes and interfaces of all assemblies to be available to the application.
Tip: A typical assembly is a. dll or. exe file, which is explained in detail in the next chapter.
Because the assembly is referenced at compile time, you can use the assembly directive to bind the assembly and then load it into the application pool at run time.
Assemblies that are located in the application set cache (that is, code files in the bin directory and the App_Code directory) are automatically connected to the application. Therefore, any assembly that is located in the bin directory, or compiled from code in the App_Code directory, does not need to use the assembly directive to implement the connection.
The assembly directive consists of two attributes: Name and SRC. The Name property is a string that represents the assembly name that is connected to the application, and it cannot contain a path. The SRC attribute is the path to the source file (relative path only), and these files are dynamically compiled and connected.
Each assembly directive can have only one property. If you need to connect multiple assemblies, you should use multiple assembly directives.
The assembly directive resembles the following:
<%@ Assembly%>
<%@ Assembly src= "Sources/somesourcefile.cs"%>
Script block
A typical Global.asax file contains a lot of code that is contained in a script block that starts and ends with a script tag:
If you use code-behind, the code in the code-behind file does not have a script tag attached to it, but the code contained in the code-behind file is equivalent to the code in the script block.
The code in the script block can contain an event handler or method, which is explained later in this article.
Event
Just as Web pages and controls can expose events, application objects and session objects in your application can also expose events. These events can be handled by the Global.asax file or the event handlers in the specified file. For example, the Application_Start event is triggered when the application starts executing, and the Application_End event is triggered when the application ends. Some of the application events are triggered whenever a page request occurs, while other events, such as Application_Error, are triggered only under certain 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 properties: One is a string named strConnectionString, and the other is an array of strings named Arbooks. The event handler method invokes a helper method named WriteFile, which is contained in the Global.asax file. The helper method writes a string to the log file. The following is the WriteFile method code in example 18-2:
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 way to log logs. This method initializes a text file-based StreamWriter object and hard-encodes the 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, which means that if the file already exists, the text line is appended to the file. If the file does not exist, a file is created.
The Application_End event handling method invokes another WriteFile method, which adds a log entry to record the end of the application.
To see the results of these two event handlers, you can make some meaningless edits to the Global.asax and save the file. This forces the end of the application. Then request any URL addresses in the virtual directory. For example, use one of the pages in the previous chapter-virtually any one-or a Web page that you create yourself. Example 18-3 shows the contents of the log file.
Example 18-3:test.txt excerpt
8/26/2006 5:46:23 PM Application starting
8/26/2006 6:13:35 PM Application ending
8/27/2006 10:17:39 PM Application starting
8/27/2006 10:18:23 PM Application ending
8/27/2006 10:18:36 PM Application starting
As with 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 method name highlighted in example 18-4, it includes all possible application event handlers in the Global.asax file. The application life cycle can be easily viewed during page requests being accepted, processed, and rendered.
Example 18-4:global.asax Event description
<%@ application language= "C #"%>
The following are all events triggered by a page request to trigger a sequential ordering:
Application_BeginRequest
triggered when ASP. NET starts processing each request. The code in this event processing will be executed before the page or service processes the request.
Application_AuthenticateRequest
Triggered before the request is validated. (as the 12th chapter describes, validation is the process of confirming that the user is the person he is talking about) in the code of this event handler allows the implementation of a custom security pipeline.
Application_authorizerequest
Triggered before authorization is granted for the request. (Authorization is the process of determining whether a user is requested to have permission to access a resource,
The 12th chapter has been introduced to allow the implementation of custom security pipelines in the code of this event handler.
Application_resolverequestcache
When ASP. NET determines whether a new output should be generated or triggered before it is populated by the cache. In either case, the code in the event handler is executed.
Application_acquirerequeststate
Executes before the session state is acquired.
Application_prerequesthandlerexecute
Triggered before a request is sent to a handler object that serves the request. When the event is triggered, the page is processed by the HTTP handler for the request.
Application_postrequesthandlerexecute
triggered when an HTTP handler is completed with a page request. At this point, the response object will get the data returned by the client.
Application_releaserequeststate
Triggered when the attempt state is released and updated.
Application_updaterequestcache
If the output is cached, it is triggered when the cache is updated.
Application_EndRequest
Executes when the request is finished.
Application_presendrequestheaders
Triggered before an HTTP header is sent to the client. If response caching is enabled, this means that no data is sent until all data is ready (the default condition). The event is always after the Application_EndRequest event. If the response cache is disabled, the event is triggered whenever the data is sent to the client. The response control is controlled by a property of the page directive, or by the WebMethod property of the Web service.
Application_presendrequestcontent
Triggered before HTTP content is sent to the client. As with the Application_presendrequestheaders event, the Application_presendrequestcontent event can be triggered depending on whether the response cache is available.
The following lists application events, which are triggered under certain conditions:
Application_Start
Triggered when the application starts. When you first request any page in the application virtual directory, the application is started, and the event is not triggered if the application is already running.
Application_End
Triggered at the end of the application. Whenever you modify a configuration file (Global.asax, Global.asax.cs,
Global.asax.vb or Web. config), or the server crashes or restarts, the application ends. Code that typically performs cleanup functions in the event handler, such as closing a database connection.
Session_Start
Triggered at the start of each session, where the specific session code is placed.
Session_End
Triggered at the end of the session. It provides an opportunity to save any data stored in the session.
Application_disposed
Triggered when the CLR removes an application from memory.
Application_Error
Fires whenever an unhandled error occurs anywhere in the application. It provides a good opportunity to implement generic application error handling.
Use the Try...catch statement block to handle specific errors in your code, or you can use the ErrorPage property of the page directive to capture page-level errors. Using these methods to handle any errors will not trigger the Application_Error event.
To test the new version of Global.asax, create a Web page in Example 18-5. View the Globalevents site. When the page runs, you will see the page shown in 18-4.
Example 18-5:globalevents Web site default.aspx
<%@ 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 18-4, you can see that a series of application events are triggered. Halfway through the execution of these events, the. aspx page itself is rendered, followed by other application events.
Warning: the example globalevents must be in a real IIS virtual path to run well.
The Session_Start event is triggered the first time the page is displayed, and the event is no longer triggered in the subsequent display. This is because the request is the same session. Click the "End Session" button to invoke the Session.Abandon method, which ends the current session. The next time the page is submitted to the server, the Session_Start event is triggered again.
The Post button provides a simple way to resubmit the page again.
Most of the application event handlers in example 18-4 use the Response.Write method to display the events that are triggered. However, the Application_Start and Application_End methods call the WriteFile method. If you try to use the Response.Write method in these event handlers, the page will not
Show. Because the page session that was used to render was not running yet. However, when you check the log file C:\test.txt, you will see the entries that appear when the application starts and ends.
The Global.asax file shown in example 18-4 illustrates a method for using the Application_Error event. These codes are listed below:
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 + "
" +
The End Error MSG
");
}
The event handler uses the GetLastError method of the HttpServerUtility object to report the last 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 errors in the current HTTP request:
Context.clearerror ()
If you do not clear the error, the error is displayed in the client browser and you still cannot see the results of the Respons-e.write method.
Finally, the Response.Write method displays a message that the current error will be displayed on the client.
Another way to report an error to a user is to display a custom error handling page. To do this, you need to replace the Response.Write method in the Application_Error event handler with the following line of code:
Response.Redirect ("Customerrorpage.aspx? Msg= "+
Server.URLEncode (strerror));
The preceding line of code invokes the UrlEncode method of the HttpServerUtility object, which passes the error message as a querystring parameter to the custom error-handling code in the Customerrorpage.aspx page. The Customerrorpage.aspx page has a label control named Lblmessage. The following is the Page_Load method code in the page:
void Page_Load (Object Source, EventArgs E)
{Lblmessage.text = request.querystring["MSG"];}
The Generate Error button in Default.aspx intentionally triggers an error to see the error handling. The code for the button's Click event handler is shown below, and it will be in addition to the 0 exception:
protected void Btnerror_click (object sender, EventArgs e)
{
int a = 5;
int b = 0;
int C;
c = A/b;
}
Server Side includes
The use of server-side includes the ability to implement the inclusion of external source code files in the application. Before compiling, the code included in the file will be added to the Global.asax file. Although the language of the application may differ from the language that includes the file, the language used to include the file must match the language used by the Global.asax file.
The following is the syntax for server-side:
In this syntax, the PathType type can be one of the examples shown in table 18-1.
Table 18-1 PathType Properties

Path type Description
File File name is the relative path to the directory that contains the Global.asax file
Virtual The file name is the virtual path that contains the Web site virtual directory



To view the Global.asax file shown in example 18-4, add the following code to the second line:

Create a new text file named IncludeFile.cs that stores the file and the Global.asax in the same directory. This file requires the same pair of script tags as the Global.asax file.

Copy the WriteFile method from the Global.asax page to the include file, and then comment (or delete) the WriteFile method in the Global.asax page. This includes the file should resemble example 18-6.

Example 18-6: Global.asax with files included

If you run any Web page, it will not be the same as before, because all you do is transfer the code from one file to another file.

If the CLR monitors changes to the Global.asax file and, like the restart application, the CLR also monitors for changes that include files. If the include file changes, the application will also restart.

Including files is useful for the same standard code that is included in multiple applications. These common code may include database access methods, write logging, error-handling pipelines, logins, or the underlying type code snippet for each application.

Object declaration

Another way to include code in a Global.asax file is to declare the OBJECT tag. The static objects of these declarations are either application or session objects. This can be used in the application or during each session.

ASP. NET Global.asax Detailed

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.