Http Module introduction http://www.tracefact.net/Asp-Net/Introduction-to-Http-Module.aspx

Source: Internet
Author: User
Introduction

In the two articles, Http request processing process and Http Handler introduction, we first understand the processing process of Http requests on the server side, then we know that the Http request will eventually be processed by the class implementing the IHttpHandler interface (remember that the Page class implements IHttpHandler ). From the last figure in the Http request processing process, we can see that before the Http request is processed by IHttpHandler, it needs to use a series of Http modules. After the request is processed, it needs to pass a series of Http modules again. How are these Http modules made up? What is used? This article describes the Http Module.

Http Module Overview

We will not consider implementing the Http Module on our own. In. Net, the Http Module is an assembly that implements the IHttpModule interface. The IHttpModule interface does not have any upper-case close-up. It can be seen from its name that it is just an ordinary interface. In fact, we are concerned about the classes that implement these interfaces. If we write code to implement this interface, what is the purpose. In general, we can set Asp.. Net events are divided into three levels: application-level events, page-level events, and control-level events, the event trigger is closely related to the application cycle, page cycle, and control cycle.The role of the HTTP module is closely related to application events.

We use the Http Module to register the method expected to respond to application events in the Http request Pipeline (Pipeline). When the corresponding event is triggered (such as the BeginRequest event, when an application receives an Http request and is about to process it), it calls the method registered by the Http Module. The actual work is executed in these methods .. Net itself already has many Http modules, including form verification Module (FormsAuthenticationModule), Session Status Module (SessionStateModule), and output cache Module (OutputCacheModule.

Register an Http Module

Before registering our own Http Module, let's take a look at the existing Http Module in Asp. Net. Similar to Http Handler, we need to open the web. CONFIG file under the C: \ WINDOWS \ Microsoft. NET \ Framework \ v2.0.50727 \ config directory on the machine. Find the

<HttpModules>
<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"/>
...
</HttpModules>

First, we can see from the node that the type attribute is similar to the type attribute of the http handler node mentioned in the previous section and represents the corresponding assembly. However, unlike http handler, the module only provides a name attribute and does not specify a specific file handler (or use wildcard * to represent a specific type) such as path. This is related to the features of the Module. We know that the module responds to events triggered during the application cycle, and all requests submitted to aspnet_isapi.dll are the same, even if the request only gets an image like a http://www.tracefact.net/images/logo.gif (after setting ISAPI, the default aspnet_isapi.dll does not take over the image file ).

Similar to HTTP handler, in our own HTTP module, assume that the class name is moduledemo, which is located in the mynamespace namespace and the Assembly name is mydll. the DLL is copied to the bin directory and stored in the web. config file system. create an httpmodules node under a web node:

<System. Web>
<Httpmodules>
<Add name = "custommodulename" type = "mynamespace. moduledemo, mydll"/>
</Httpmodules>
</System. Web>

The Type attribute is divided into two parts: namespace and class name, that is, type name; followed by the Set Name. If we create the code in the app_code directory, you do not need to specify the Set Name.

The name attribute is named by ourselves, not necessarily the same as the class name. Here I name it "mmmodulename ". We can get the httpmodulecollection through the modules attribute of the application (httpapplication), and then get the httpmodule object through the name attribute.

Through the name attribute, we can also. in the asax file, compile the event processing program exposed by the custom httpmodule. The format is void modulename_eventname (Object sender, eventargs E ). We will give a more detailed introduction later.

Http Modules built in Asp. Net

The following table lists the Http Modules built in Asp. NET in Web. CONFIG under C: \ WINDOWS \ Microsoft. Net \ Framework \ v2.0.50727 \ Config and their main functions.

Name Type Function
OutputCache System. Web. Caching. OutputCacheModule Page-level output Cache
Session System. Web. SessionState. SessionStateModule Session Status Management
WindowsAuthentication System. Web. Security. WindowsAuthenticationModule Use integrated Windows authentication for client authentication
FormsAuthentication System. Web. Security. FormsAuthenticationModule Client authentication using Cookie-based form Authentication
PassportAuthentication System. Web. Security. PassportAuthenticationModule Customer identity verification with MS passport
RoleManager System. Web. Security. RoleManagerModule Manage current user roles
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 Manage anonymous access in Asp. Net Applications
Profile System. Web. Profile. ProfileModule Manage the creation of user archive files and related events
ErrorHandlerModule System. Web. Mobile. ErrorHandlerModule Capture exceptions, format error message characters, and pass them to the client program

We will program it later.

IHttpModule Interface

After reading so much theoretical knowledge, this section will start to write some programs to implement your own Http Module. First, let's take a look at the IHttpModule interface, which includes the following two methods:

Public void Init (HttpApplication context );
Public void Dispose ();

Init (): This method accepts an HttpApplication object. HttpApplication represents the current application, and we need to register the event where the HttpApplication object is exposed to the client in this method. It can be seen that this method is only used to register events, and the actual event processing program requires us to write another method.

The entire process is well understood:

  1. When the first resource of the site is accessed, Asp. net will create an httpapplication class instance, which represents the site application, at the same time will create all in the web. the module instance that has been registered in config.
  2. The module Init () method is called when a module instance is created.
  3. Register the events exposed by the httpapplication that you want to respond to in the init () method. (Only simple registration of methods is required. The actual method needs to be written separately ).
  4. Httpapplication triggers various events in its application cycle.
  5. When an event is triggered, call the method that the module has registered in its Init () method.

Note: If you do not know about event registration and other related content, see the delegate and event article in C.

Dispose (): It can be cleaned up before garbage collection.

To sum up, an IHttpModule template is generally like this:

Public class ModuleDemo: IHttpModule
{
Public void Init (HttpApplication context ){
// Register the HttpApplication BeginRequest event
// It can also be an event exposed by any other HttpApplication.
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. The HttpContext object is obtained, and the rest can be used freely.
}

Public void Dispose (){
}
}

Write text to the Http request output stream through the Http Module

In this example, we only use the BeginRequest event and EndRequest event to describe how to use the Http Module. This example shows how to use the Http Module.

First, create a new site and add the class file: ModuleDemo. cs: To the App_Code directory:

Public class ModuleDemo: IHttpModule
{
// The Init method is only used to register the method for the expected event
Public void Init (HttpApplication context ){
Context. BeginRequest + = new EventHandler (context_BeginRequest );
Context. EndRequest + = new EventHandler (context_EndRequest );
}

// The actual code used to process the BeginRequest event
Void context_BeginRequest (object sender, EventArgs e ){
HttpApplication application = (HttpApplication) sender;
HttpContext context = application. Context;
Context. Response. Write ("

}

// The actual code used to process 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 above code is very simple. It registers the BeginRequest event and EndRequest event of the HttpApplication instance. The event processing method is only used at the beginning and end of the http request, write different content to the input stream of the http request.

Next, write the following content in the System. Web node of web. config:

<System. web>
<HttpModules>
<Add name = "MyModule" type = "ModuleDemo"/>
</HttpModules>
</System. web>

Then, open the Default. aspx file automatically created when the site is created, and type a few words in it. To differentiate it, I entered the text on the. aspx page. Then, open it in the browser and you will see something like this:

Then we create a new Default2.aspx, Which is browsed in the browser. We can see that the two pages have the same effect. This indicates that the http Module works for different two files. It can be seen that it is indeed at the application level rather than the page level.

Now, we open an image file on the site and find that it shows a Red Cross. Why? Because the Http Module is for an http request, rather than a certain type of files, when requesting an image, the http Module we wrote will still work and insert the text into the binary image, if the file format is damaged, only the Red Cross is displayed.

NOTE:Don't be surprised if you find that your images are normally displayed. The thing is this: Let's look back at the first section we discussed. For image files, they are directly processed by IIS and will not be handed over to aspnet_isapi.dll, therefore, the Module cannot capture requests for image files. The solution is to set it in IIS.
Note that if you use the Local Server that comes with Vs2005, you do not need to set IIS. All images or any file types will be processed by aspnet_isapi.dll.

Traverse the Http Module set

Now, we can traverse the HttpModuleCollection set to view the names of all the Http modules registered to the application.

Create a file RegisteredModules. aspx and add the following method to the Code POST file:

Private string ShowModules (){
HttpApplication app = Context. ApplicationInstance; // obtain the HttpApplication environment of the current Context
HttpModuleCollection moduleCollection = app. Modules; // gets all Module Sets

// Obtain the names of all modules
String [] moduleNames = moduleCollection. AllKeys;

System. Text. StringBuilder results = new System. Text. StringBuilder (); // traverses the result set

Foreach (string name in moduleNames ){
// Obtain the Module name
Results. Append ("<B style = 'color: #800800 '> name:" + name + "</B> <br/> ");
// Obtain the Module type
Results. Append ("type:" + moduleCollection [name]. ToString () + "<br/> ");
}

Return results. ToString ();
}

Then output the following in the Page_Load method:

Protected void Page_Load (object sender, EventArgs e)
{
Response. Write (ShowModules ());
}

We can see the following picture:

Compared with the table listed above, we can see that it is almost identical (with an additional DefaultAuthentication ). In addition, in the last and last lines of attention, isn't the Module defined by ourselves? The name is MyModule and the type is ModuleDemo.

Global. asax file and Http Module

As early as the asp era, everyone knows this file. It is mainly used to place responses to application events or Session events. You are familiar with Application_Start, Application_End, Session_Start, and Session_End.

In asp.net, Glabal not only registers applications and Session events, but also registers events exposed by the Http Module. It can not only register system Module events, you can also register the events exposed by our own Module. Before proceeding to the specific introduction, pay attention to the following two points:

  1. Each time an Http request is processed, the application event is triggered again, except Application_Start and Application_End. This event is triggered only when the first resource file is accessed.
  2. The Http Module cannot register and respond to Session events. For Session_Start and Session_End, they can only be handled through Glabal. asax.

Now let's modify the previous ModuleDemo sample program and add an event to it as follows (to simplify the program, I simplified it ):

Public class ModuleDemo: IHttpModule {

// Declare an event
Public event EventHandler ExposedEvent;

// The Init method is only used to register the method for the expected event
Public void Init (HttpApplication context ){
Context. BeginRequest + = new EventHandler (context_BeginRequest );
}

// The actual code used to process 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 THE METHOD
}

Protected override void OnExposedEvent (EventArgs e ){
If (ExposedEvent! = Null) // If registered in Global
ExposedEvent (this, e); // call the registered Method
}

Public void Dispose (){
}
}

Next, create a Global. asax file in the site and add the following code to it. Note that the format is void module name_event name (object sender, EventArgs e ).

Void MyModule_ExposedEvent (object sender, EventArgs e)
{
Response. Write ("<H3 style = 'color: #800800 '> text from global. asax </H2> ");
}

Now, we can see this on the previous page. We have successfully linked the glabal. asax file to the event exposedevent exposed by our custom HTTP module:

Summary

This article briefly introduces what is an HTTP module. We first understood the role of the HTTP module, and then checked ASP. net built-in module, then we introduced the ihttpmodule interface, and implemented this interface through a simple example, finally we discussed HTTP module and global. asax file contact.

This article only briefly introduces the ihttpmodule and adds more practical applications to subsequent articles.

I hope this article will help you!

Related Article

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.