Go to the-Global. asax file (site counter)

Source: Internet
Author: User

Use global. asax as the site Technician:

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

<Script runat="Server">

Void Application_start ( Object Sender, eventargs E)
{
// In the ApplicationProgramTheCode
System. Io. streamreader SRD =   New System. Io. streamreader (server. mappath ( " Counter.txt " ));
Int Count =   Int . Parse (SRD. Readline ());
Application. Lock ();
Application [ " Count " ] = Count;
Application. Unlock ();
SRD. Close ();
}

Void Application_end ( Object Sender, eventargs E)
{
// Code that runs when the application is closed
System. Io. streamwriter SWT =   New System. Io. streamwriter (server. mappath ( " Counter.txt " ));
SWT. writeline (application [ " Count " ]);
SWT. Close ();
}

Void Application_error ( Object Sender, eventargs E)
{
// Code that runs when an unprocessed error occurs

}

Void Session_start ( Object Sender, eventargs E)
{
// Code that runs when a new session is started
Application. Lock ();
Application [ " Count " ] = Convert. toint16 (application [ " Count " ]) +   1 ;
Application. Unlock ();
System. Io. streamwriter SWT =   New System. Io. streamwriter (server. mappath ( " Counter.txt " ));
SWT. writeline (application [ " Count " ]);
SWT. Close ();
}

Void Session_end ( Object Sender, eventargs E)
{
// The code that runs when the session ends.
// Note: Only the sessionstate mode in the web. config file is set
// In inproc, The session_end event is triggered. If the session mode is set to StateServer
// Or sqlserver.
System. Io. streamwriter SWT =   New System. Io. streamwriter (server. mappath ( " Counter.txt " ));
SWT. writeline (application [ " Count " ]);
SWT. Close ();
}
/* Then, you can use the appliation ["count"] object to display the counter on the webpage. */
</ Script >

PS: The counter.txt file is created first when the formula for reading and writing files is used. Otherwise, an error is reported.

PS:Then, you can use the appliation ["count"] object to display the counter on the webpage.

 

 

 

 

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.

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 downloading the applicationSource codeASP. NET is configured by default to prevent users from viewing 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. 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.

The source code is as follows:

< % @ Application Language = "C #" % >
< Script Runat = "Server" >
Void application_start (Object sender, eventargs E)
{
// Code that runs when the application starts
}
Void application_end (Object sender, eventargs E)
{
// Code that runs when the application is closed
}
Void application_error (Object sender, eventargs E)
{
// Code that runs when an unhandled error occurs
}
Void session_start (Object sender, eventargs E)
{
// The code that runs when the new session starts
}
Void session_end (Object sender, eventargs E)
{
// The code that runs when the session ends.
// Note: Only the sessionstate mode in the web. config file is set
// The session_end event is triggered only when inproc is used. If the session mode is set to StateServer
// Or sqlserver, the event is not triggered.
}
</ Script >

L 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 accept one or more attribute/value pairs with dictionary structures. Three commands are supported: application, import, and assembly.

ApplicationApplication CommandSet the application-specific properties 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 correspond to vb2005, C #, JScript. net, or J # respectively #. (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.

ImportImport commandOnly one namespace attribute is included. 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.

AssemblyAssembly commandUsed 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 A. dllor. EXE file.
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 name = "someassembly" %>
<% @ 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:
<SCRIPT runat = "server">
-------
</SCRIPT>
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 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.) The event handler Code allows the implementation of custom security pipelines.
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. No matter when the configuration file (Global. asax, global. asax. CS, global. asax. VB, or web. config) is modified, or the server crashes or restarts, the application ends. 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 the CLR removes an application from the memory.
application_error

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.