Introduction
HTTP request processing process and HTTP Handler introduction These two articles, we first understand the HTTP request on the server side of the processing process, and then we know that the HTTP request will eventually be implemented by the IHttpHandler interface of the class processing ( You should remember that the page class implements IHttpHandler. As you can see from the last illustration of the HTTP request processing process, it needs to pass through a series of HTTP module before the HTTP request is processed by IHttpHandler, and after the request is processed, it needs to pass through a series of HTTP module, then the HTTP How the module is composed. What to do with it. This article describes the HTTP module. Http Module Overview
For the time being we do not consider our own implementation of HTTP module. In. NET, Http Module is an assembly that implements the IHttpModule interface. The IHttpModule interface itself has nothing to capitalize on, and by its name it can be seen as just an ordinary interface. In fact, we are concerned with the classes that implement these interfaces, and if we also write code that implements this interface, what is the use. In general, we can divide the events in asp.net into three levels, the topmost of which is the application-level event, the second is the page-level event, the bottom is the control-level event, and the triggering of the event is closely related to the application cycle, the page cycle, and the control cycle. The role of Http Module is closely related to application events.
We register a method in the HTTP request pipeline (Pipeline) that expects to respond to application events through HTTP module, when the corresponding event is triggered (for example, the BeginRequest event, It fires when an application receives an HTTP request and is about to be processed, and the HTTP module-registered method is invoked, and the actual work is performed in these methods.. Net itself already has a number of HTTP Module, including form validation module ( FormsAuthenticationModule), Session state module (sessionstatemodule), output cache module (OutputCacheModule), and so on. Registering Http Module
Before registering the Http Module we wrote ourselves, let's look at the HttpModule already in the asp.net. Like the Http handler, we need to open the Web.config file on the C:/windows/microsoft.net/framework/v2.0.50727/config directory on the machine. Find
<add name= "OutputCache type=" System.Web.Caching.OutputCacheModule "/>
<add name=" session "Type=" System.Web.SessionState.SessionStateModule "/>
<add name=" WindowsAuthentication "type= "System.Web.Security.WindowsAuthenticationModule"/>
<add name= "FormsAuthentication" Type= "System.Web.Security.FormsAuthenticationModule"/>
<add name= " Passportauthentication "type=" System.Web.Security.PassportAuthenticationModule/>
< Add Name= "rolemanager" type= "System.Web.Security.RoleManagerModule"/>
<add name= " URLAuthorization "type=" System.Web.Security.UrlAuthorizationModule "/>
... Slightly
Let's start with the node. The Type property is similar to the type attribute of the HTTP handler node as described in the previous section, and represents the appropriate assembly. However, unlike HTTP handler, the module provides only a Name property, and no handlers such as path specify a particular (or wildcard * representing a certain kind of) file. This is related to the characteristics of module, and we know that the module is responding to events triggered in the application cycle, and that all requests submitted to Aspnet_isapi.dll are the same, even if the request is just like a http://www.tracefact.net/ Images/logo.gif get a picture like this (after setting up the ISAPI, the default aspnet_isapi.dll does not take over the picture file).
Similar to HTTP handler, in this book our own HTTP module, assuming the class name is Moduledemo, is located under the MyNamespace namespace, the assembly name is Mydll, We simply copy the MyDll.dll to the bin directory and create the httpmodules node under the site's Web.config file system.web node:
<system.web>
<add name= "Custommodulename" type= "Mynamespace.moduledemo, Mydll"/>
</system.web>
The type attribute is divided into two parts, preceded by a namespace and class name, which is the type name, followed by the assembly name. If we create the code in the App_Code directory, you do not need to specify the assembly name again.
The Name property is named by us, not necessarily the same as the class name, which I name as "Custommodulename". We can get the Httpmodulecollection collection from the Modules property of the application (HttpApplication), and then get the HttpModule object further through the Name property.
With the Name property, we can also write a handler for a custom HttpModule exposed event in a Global.asax file in the form of void Modulename_eventname (object sender, EventArgs e). We will explain in more detail later. asp.net built in Http Modules
The following table lists the ASP.net built-in HTTP Modules and its primary role in the web.config under C:/windows/microsoft.net/framework/v2.0.50727/config.
Name |
Type |
Function |
OutputCache |
System.Web.Caching.OutputCacheModule |
Page-Level output caching |
Session |
System.Web.SessionState.SessionStateModule |
Session state Management |
WindowsAuthentication |
System.Web.Security.WindowsAuthenticationModule |
Client-side validation with Integrated Windows authentication |
FormsAuthentication |
System.Web.Security.FormsAuthenticationModule |
Client Authentication with cookie-based forms authentication |
Passportauthentication |
System.Web.Security.PassportAuthenticationModule |
Client Authentication with MS Passport |
RoleManager |
System.Web.Security.RoleManagerModule |
Managing the current User role |
URLAuthorization |
System.Web.Security.UrlAuthorizationModule |
Determine whether a user is authorized to access a URL |
Fileauthorization |
System.Web.Security.FileAuthorizationModule |
Determine whether a user is authorized to access a resource |
anonymousidentification |
System.Web.Security.AnonymousIdentificationModule |
Managing anonymous access in an ASP.net application |
Profile |
System.Web.Profile.ProfileModule |
Manage the creation of user profiles and related events |
Errorhandlermodule |
System.Web.Mobile.ErrorHandlerModule |
Catch exception, format error prompt character, pass to client program |
We'll look at it in a programmatic way later. IHttpModule Interface
Having read so much theoretical knowledge, this section will begin to write a point program to implement your own HTTP Module. We first need to look at the IHttpModule interface, which includes the following two methods:
public void Init (HttpApplication context);
public void Dispose ();
Init (): This method accepts a HttpApplication object, HttpApplication represents the current application, and we need to register the event that the HttpApplication object exposes to the client within this method. Visible, this method is only used to register the event, and the actual event handler, we need to write a different method.
The whole process is well understood: when the site's first resource is accessed, ASP.net creates an instance of the HttpApplication class that represents the site application and creates all of the module instances registered in Web.config. The init () method of module is invoked when creating a module instance. In the Init () method, register the event exposed by the HttpApplication that you want to respond to. (Simply register for the method, the actual method needs to be written separately). HttpApplication triggers various events in its application lifecycle. Invokes the method that module has registered in its init () method when the event is triggered.
Note: If you do not understand event registration and other related content, see the article on delegates and events in C #.
Dispose (): It can perform some cleanup work before garbage collection is done.
To sum up: to implement a ihttpmodule template is generally like this:
public class Moduledemo:ihttpmodule
{
public void Init (HttpApplication context) {
Registering HttpApplication application beginrequest events
It could be any other httpapplication exposure.
Context. BeginRequest + = new EventHandler (context_beginrequest);
}
void Context_beginrequest (object sender, EventArgs e) {
HttpApplication application = (HttpApplication) sender;
HttpContext context = Application. context;
Do some practical work, HttpContext objects are obtained, the rest of the basic can be free to play
}
public void Dispose () {
}
write text to the HTTP request output stream through HTTP module
In this case, we only use the BeginRequest event and the EndRequest event to illustrate the use of Http Module. We use this example to understand the basic usage of Http Module.
First, create a new site and add the class file to the App_Code directory: ModuleDemo.cs:
public class Moduledemo:ihttpmodule
{
The Init method is used only to register methods for the expected event
public void Init (HttpApplication context) {
Context. BeginRequest + = new EventHandler (context_beginrequest);
Context. endrequest + = new EventHandler (context_endrequest);
}
The actual code to handle the BeginRequest event
void Context_beginrequest (object sender, EventArgs e) {
HttpApplication application = (HttpApplication) sender;
HttpContext context = Application. context;
Context. Response.Write ("
}
The actual code to handle the EndRequest event
void Context_endrequest (object sender, EventArgs e) {
HttpApplication application = (HttpApplication) sender;
HttpContext context = Application. context;
Context. Response.Write ("}
public void Dispose () {
}
}
The code above is simple, it registers the BeginRequest event and the endrequest event of the HttpApplication instance, and the event-handling method simply writes different content to the HTTP request's input stream at the beginning and end of the HTTP request.
Next, write the following in the system.web node of web.config:
<system.web>
<add name= "MyModule" type= "Moduledemo"/>
</system.web>
Then, open the Default.aspx file created automatically when you set up the site, and make a few words inside, and to make a distinction, I enter the text that is on the. aspx page. Then we open it in the browser and we should see something like this:
Then we create a new default2.aspx, browse in the browser, you can see that two pages have the same effect. This means that HTTP module works for different two files, which is visible at the application level rather than at the page level.
Now, we open a picture file in the site, found that the display is a red fork, why. Because HTTP module is for HTTP requests, not for one or a certain type of file, the HTTP module we write will still work when a picture is requested, inserting text into binary images, destroying the file format, and naturally displaying a red fork.
Note : If you find that your picture appears normal, please do not be surprised, the thing is this: recall the first section we discussed, for picture files, directly handled by IIS, and will not be referred to aspnet_ Isapi.dll, therefore, module cannot capture requests for picture type files. The workaround is to set it up in IIS.
The point to note here is that if you use Vs2005 's own local Server, you do not have to set up IIS, and all images and any file types will be handled by Aspnet_isapi.dll. traversing the HTTP module collection
Now we're going to iterate through the Httpmodulecollection collection to see the names of all Http Module registrations to the application.
Create a new file registeredmodules.aspx and add the following method to the code post file:
Private String Showmodules () {
HttpApplication app = context.applicationinstance; Gets the HttpApplication environment for the current context
httpmodulecollection modulecollection = App. Modules; Get all module Collections
/Get all module names
string[] Modulenames = Modulecollection.allkeys;
System.Text.StringBuilder results = new System.Text.StringBuilder (); // Traversal result set
foreach (string name in Modulenames) {
// Get the module name
results. Append ("<b style= ' color: #800800 ' > Name:" + name + "</b><br/>");
//Get module type
results. Append ("type:" + modulecollection[name]. ToString () + "<br/>");
}
return results. ToString ();
}
And then output in the Page_Load method:
protected void Page_Load (object sender, EventArgs e)
{
Response.Write (Showmodules ());
}
We should be able to see the following picture:
Compared to the table listed earlier, you can see that it is almost identical (one more defaultauthentication). Also note the fourth line of the last figure, which is not our own definition of module. Name is MyModule and the type is Moduledemo. Global.asax file with Http Module
As early as in the ASP era, everyone knows this file. It is primarily used to place a response to an application event or session event. We are familiar with Application_Start, Application_End, Session_Start, Session_End and so on.
In asp.net, Glabal can register not only the application and session events, but also the events exposed by the HTTP module, not only the events of system module, but also the events exposed by our own literal module. Before we go into specifics, here's the first two points to note: Application events are triggered every time an HTTP request is processed, but Application_Start and application_end exceptions are triggered only when the first resource file is accessed. Http module cannot register and respond to session events, and for Session_Start and Session_End, it can only be handled through Glabal.asax.
OK, so now we're going to modify the Moduledemo sample program and give it an event like this (to make the program simpler, I simplify):
public class Moduledemo:ihttpmodule {
Declaring an Event
public event EventHandler Exposedevent;
The Init method is used only to register methods for the expected event
public void Init (HttpApplication context) {
Context. BeginRequest + = new EventHandler (context_beginrequest);
}
The actual code to handle the BeginRequest event
void Context_beginrequest (object sender, EventArgs e) {
HttpApplication application = (HttpApplication) sender;
HttpContext context = Application. context;
Context. Response.Write ("
Onexposedevent (New EventArgs ()); Call method
}
protected override void Onexposedevent (EventArgs e) {
if (exposedevent!= null)//If there is a registration in global
Exposedevent (this, e); Calling a registered method
}
public void Dispose () {
}
}
Next, we create a Global.asax file in the site, add the following code inside, and note that the format is: void Module Name _ Event name (object sender, EventArgs e).
void Mymodule_exposedevent (object sender, EventArgs e)
{
Response.Write ("
}
Now that we've opened the previous page, it should be seen that we have successfully linked the Glabal.asax file to the event Exposedevent exposed by our own defined HTTP module:
Summary
This article briefly describes what an HTTP Module is. We first understood the role of Http module, then looked at the ASP.net built-in module, then we introduced the IHttpModule interface, and through a simple example to implement this interface, finally we discussed the HTTP module and Global.asax file.
This article is just a brief introduction to IHttpModule, more practical applications, will be supplemented in subsequent articles.
I hope this article will help you.