Master the Global.asax of VS2008 in the special place

Source: Internet
Author: User
Tags decrypt httpcontext sessions
When you use VS2005 or VS2008 to design your system and add a global control file global.asax, VS2003 the above versions are not Global.asax.cs files by default. In other words, only the processing code can be written directly into the Global.asax file, and the background code library is no longer available. But in this case, it is no problem to run the virtual window or open source, but after compiling the problem comes, and it makes people very headache.
After compiling the Global.asax file does not exist, I guess it is in the VS to compile the code in the Global.asax into the App_Code (just guess, if someone can tell me the correct answer I would be grateful). An error occurred after a compiled system that disappeared global.asax. The light does not execute the intended content, and the heavy is directly unable to run. So, is there a solution? Here to tell you. Actually this answer is I looked for on the net, but the concrete source does not remember.
First, add a Global.asax.cs file, preferably with a namespace, to the App_Code before compiling, and then change the public class Global to be based on the HttpApplication type.
C # code
Public
Class Global:httpapplication {
Public Global () {
//
Todo:add constructor Logic here
//    } }
Finally, the process of Global.asax itself can be written. And the Global.asax file at the front desk is just written <%@ Application inherits= "name space. Global "language=" C #%>。 To prevent errors, it is a good idea to add the original Global.asax file's assembly name (although not added) after compiling.
This is the complete solution.
PS: Microsoft has been doing some headache problems out ...


Global.asax files, sometimes called asp.net application files, provide a way to respond to application-level or module-level events in a central location. You can use this file to implement security for your application and some other tasks. Let's take a look at how to use this file in the application development effort.

Overview

Global.asax is located in the application root directory. Although Visual Studio. NET automatically inserts this file into all ASP.net projects, it is actually an optional file. It doesn't matter if you delete it--of course, if you don't use it. The asax file name extension indicates that it is an application file, not a asp.net file that uses ASPX.

The Global.asax file is configured for any direct HTTP request (via URL) to be rejected automatically, so the user cannot download or view its contents. The ASP.net page framework automatically identifies any changes made to the Global.asax file. After the Global.asax is changed, the asp.net page framework restarts the application, including closing all browser sessions, removing all state information, and restarting the application domain.

Programming

The Global.asax file inherits from the HttpApplication class, which maintains a pool of HttpApplication objects and assigns objects from the object pool to the application when needed. The Global.asax file contains the following events:

· Application_init: This event is triggered when an application is instantiated or when it is invoked for the first time. It will be invoked for all HttpApplication object instances.

· Application_disposed: Triggers before the application is destroyed. This is the ideal place to clear previously used resources.

· Application_Error: The event is triggered when an unhandled exception is encountered in the application.

· Application_Start: The event is triggered when the first instance of the HttpApplication class is created. It allows you to create objects that can be accessed by all HttpApplication instances.

· Application_End: The event is triggered when the last instance of the HttpApplication class is destroyed. It is only triggered once in the life cycle of an application.

· Application_BeginRequest: Triggered when an application request is received. For a request, it is the first event that is triggered, and the request is typically a page request (URL) entered by the user.

· Application_EndRequest: The last event requested for the application.

· Application_prerequesthandlerexecute: The event is triggered before the ASP.net page framework starts executing an event handler such as a page or Web service.

· Application_postrequesthandlerexecute: The event is triggered when an event handler is executed at the end of the ASP.net page frame.

· Applcation_presendrequestheaders: The event is triggered when the ASP.net page frame sends an HTTP header to the requesting client (browser).

· Application_presendcontent: This event is triggered when the ASP.net page frame sends content to the requesting client (browser).

· Application_acquirerequeststate: When the asp.net page frame gets the current state (session state) associated with the current request, the event is triggered.

· Application_releaserequeststate: This event is triggered when all event handlers are executed in the ASP.net page framework. This will cause all the state modules to hold their current state data.

· Application_resolverequestcache: The event is triggered when an authorization request is completed on the ASP.net page frame. It allows caching modules to service requests from the cache, bypassing the execution of event handlers.

· Application_updaterequestcache: When the asp.net page framework completes execution of an event handler, the event is triggered so that the cache module stores the response data for use in response to subsequent requests.

· Application_AuthenticateRequest: This event is triggered when the security module establishes a valid identity for the current user. At this point, the user's credentials will be validated.

· Application_authorizerequest: The event is triggered when the security module confirms that a user can access the resource.

· Session_Start: The event is triggered when a new user accesses the application Web site.

· Session_End: This event is triggered when a user's session times out, ends, or when they leave the application Web site.

This list of events may seem intimidating, but these events can be very useful in different contexts.

One of the key issues in using these events is to know the order in which they are triggered. The Application_init and Application_Start events are triggered once the application is first started. Similarly, application_disposed and Application_End events are triggered once when the application terminates. In addition, session-based events (Session_Start and session_end) are used only when the user enters and leaves the site. The remaining events handle application requests, which are triggered in the following order:

· Application_BeginRequest

· Application_AuthenticateRequest

· Application_authorizerequest

· Application_resolverequestcache

· Application_acquirerequeststate

· Application_prerequesthandlerexecute

· Application_presendrequestheaders

· Application_presendrequestcontent

· << Execute Code >>

· Application_postrequesthandlerexecute

· Application_releaserequeststate

· Application_updaterequestcache

· Application_EndRequest

These events are often used for security purposes. The following example of C # illustrates a different Global.asax event, which uses the Application_authenticate event to complete the form based authentication of the cookie. In addition, the Application_Start event populates an application variable, while session_start fills a session variable. The Application_Error event displays a simple message indicating the error that occurred.

protected void Application_Start (Object sender, EventArgs e) {
application["Title"] = "builder.com Sample";
}
protected void Session_Start (Object sender, EventArgs e) {
session["Startvalue"] = 0;
}
protected void Application_AuthenticateRequest (Object sender, EventArgs e) {
Extract The Forms authentication Cookies
string cookiename = Formsauthentication.formscookiename;
HttpCookie Authcookie = Context.request.cookies[cookiename];
if (null = = Authcookie) {
There is no authentication cookie.
Return
}
FormsAuthenticationTicket AuthTicket = null;
try {
AuthTicket = Formsauthentication.decrypt (Authcookie.value);
catch (Exception ex) {
Log exception Details (omitted for simplicity)
Return
}
if (null = = AuthTicket) {
Cookie failed to decrypt.
Return
}
When the ticket is created, the UserData property is assigned
A pipe delimited string of role names.
STRING[2] Roles
Roles[0] = "one"
ROLES[1] = "Two"
Create an Identity object
FormsIdentity id = new FormsIdentity (AuthTicket);
This principal'll flow throughout the request.
GenericPrincipal principal = new GenericPrincipal (ID, roles);
Attach the new principal object to the current HttpContext object
Context.User = Principal;
}
protected void Application_Error (Object sender, EventArgs e) {
Response.Write ("Error encountered.");
}

This example simply uses the events in some global.asax files, and it is important to realize that these events are related to the entire application. In this way, all the methods put in it are provided through the application's code, which is why its name is global.

Here is the previous example of the corresponding vb.net code:

Sub Application_Start (ByVal sender as Object, ByVal e as EventArgs)
Application ("Title") = "builder.com Sample"
End Sub
Sub session_start (ByVal sender as Object, ByVal e as EventArgs)
Session ("Startvalue") = 0
End Sub
Sub Application_AuthenticateRequest (ByVal sender as Object, ByVal e As
EventArgs)
' Extract The Forms authentication cookie
Dim CookieName as String
CookieName = Formsauthentication.formscookiename
Dim Authcookie as HttpCookie
Authcookie = Context.Request.Cookies (cookiename)
If (Authcookie is Nothing) Then
' There is no authentication cookie.
Return
End If
Dim AuthTicket as FormsAuthenticationTicket
AuthTicket = Nothing
Try
AuthTicket = Formsauthentication.decrypt (authcookie.value)
Catch ex as Exception
' Log exception details (omitted for simplicity)
Return
End Try
Dim roles (2) as String
Roles (0) = "one"
Roles (1) = "Two"
Dim ID as FormsIdentity
id = New formsidentity (authticket)
Dim principal as GenericPrincipal
Principal = New GenericPrincipal (ID, roles)
' Attach the new principal object to the current HttpContext object
Context.User = Principal
End Sub
Sub Application_Error (ByVal sender as Object, ByVal e as EventArgs)
Response.Write ("Error encountered.")
End Sub

Resources

The Global.asax file is the central point of the ASP.net application. It provides countless events to handle different application-level tasks, such as user authentication, application startup, and processing of user sessions. You should be familiar with this optional file, so you can build a robust asp.net application.

The total number of visitors to the Web application and the number of people online will be implemented using the above event programs provided in Global.asax. The main use of application and

Session two.
For the total number of visitors, because it is from the web, so to save this value, there are two ways to save, one is the database, the other is to use the file save, here will be two

The code for the method is as follows:

Method One: Use the database to realize.

Select SQL to create a database countpeople, which has a basic table:
CREATE TABLE Countnum
(
Num INT,
)
Initializes its value to 0,
Some of the Global.asax code are as follows:
protected void Application_Start (Object sender, EventArgs e)
{
SqlConnection con=new SqlConnection ("server=.; database=countpeople;uid=sa;pwd=; ");
Con. Open ();
SqlCommand cmd=new SqlCommand ("SELECT * from Countnum", con);
int Count=convert.toint32 (cmd. ExecuteScalar ());
Con. Close ();
application["Total"]=count;
application["Online"]=0;
}

protected void Session_Start (Object sender, EventArgs e)
{
session.timeout=20;//unit is divided, the system defaults to 20min, you can customize
Application.lo can be customized
Application.Lock ();
application["Total"]= (int) application[the "total"]+1;
application["Online"]= (int) application["online"]+1;
Application.UnLock ();
protected void Session_End (Object sender, EventArgs e)
{
Application.Lock ();
application["Online"]= (int) application["online"]-1;
Application.UnLock ();

}

protected void Application_End (Object sender, EventArgs e)
{
SqlConnection con=new SqlConnection ("server=.; database=countpeople;uid=sa;pwd=; ");
Con. Open ();
SqlCommand cmd=new SqlCommand ("Updata countnum set num=" +application["Total"). ToString (), con);
Cmd. ExecuteNonQuery ();
Con. Close ();
}
This can be done in the code of the Web as follows:
private void Page_Load (object sender, System.EventArgs e)
{
this.lbltotal.text=application["Total"]. ToString ();
this.lblonline.text=application["Online"]. ToString ();
}

Where Lbltotal and Lblonline are two labels in the web window, according to type object, so add one minus one and output the

When you want to do type conversion. As above application["total"]. ToString () and so on.
The Application_Start event above is executed at the time the application is started, and Session_Start is executed at every session, so whenever a new user arrives is

Session_Start will be executed, so that both the historical number and the number of online increase by 1, but when the user exits, the end of the conversation, so that the number of people online minus 1.
The above mentioned session.timeout=20 is after the user initiates the reply, but has not carried on any dialog, the server waits for 20mins to be able to automatically shut down this reply. Than

Like now you have opened a website, but now you have to go away, 20mins has not come back, although the page is still in, but on the server side, has ended the reply program.
The above program because of using the database said to be in the namespace do not forget to add using System.Data.SqlClient;

Method two, using file storage history number:
Where the code for the Web and Session_Start (), Session_End () are the same as above, the database is changed to file storage in application's two programs:


protected void Application_Start (Object sender, EventArgs e)
{
String sFileName;
BinaryReader Fileread;
int count=0;
Sfilename=server.mappath ("/usrcount.txt"); Get the path of the text
if (file.exists (sfilename))//text exists, read data directly
{
Fileread=new BinaryReader (File.openread (sfilename));
Count=fileread.readint32 ();
Fileread.close ();
}
Else
count=0;
application["Total"]=count;
application["Online"]=0;
application["Filename"]=sfilename;
}
protected void Application_End (Object sender, EventArgs e)
{
String sFileName;
BinaryWriter FileWrite;
int count;
sfilename=application["Filename"]. ToString ();
if (file.exists (sFileName))
Filewrite=new BinaryWriter (File.openwrite (sfilename));
else//text does not exist, create
Filewrite=new BinaryWriter (File.create (sfilename));
count= (int) application["Total"];
Filewrite.write (count); Writing text
Filewrite.close ();}

=================================================================

Example: setting in Global.asax file
Sub session_start (ByVal sender as Object, ByVal e as EventArgs)
' Code that runs when a new session starts
Session.Timeout = 30
End Sub

Sub Session_End (ByVal sender as Object, ByVal e as EventArgs)
' Code that runs at the end of the session.
' Note: Only the sessionstate mode in the Web.config file is set to
' InProc, the Session_End event is raised. If the session mode is set to StateServer
' or SQL Server, the event is not raised.
Session ("AAA") = ""
Session.clear ()
Session.Abandon ()
End Sub

Web.config file Settings:
<system.web>
<sessionstate mode = "InProc" timeout = "a"/>
</system.web>

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.