Http Module Introduction

Source: Internet
Author: User

Introduction

HTTP request processing flow and HTTP Handler introduction in these two articles, we first understand the process flow of HTTP requests on the server side, and then we know that the HTTP request will eventually be processed by the class that implements the IHttpHandler interface ( You should remember that the page class implements IHttpHandler). As you can see from the last image of the HTTP request processing flow article, before the HTTP request is processed by IHttpHandler, it needs to pass through a series of HTTP module, and after the request processing it needs to pass through a series of HTTP module again, then these HTTP How is the module composed? What do you use it for? The HTTP module is described in this article.

Http Module Overview

For the time being, let's not consider our own implementation of the HTTP module. In. NET, the Http Module is an assembly that implements the IHttpModule interface. The IHttpModule interface itself has no good capitalization close-up, it can be seen by its name, it is just an ordinary interface. In fact, what we care about is the class that implements these interfaces, and if we also write code to implement this interface, then what is the use of it? In general, we can divide the events in ASP. Three levels, the topmost is the application-level event, the next is the page-level event, the bottom is the control-level event, the event's triggering is closely related to the application cycle, the page cycle, the control cycle. The role of the Http Module is closely related to application events.

We register a method in the HTTP request pipeline (Pipeline) that expects to react to an application event through the HTTP module, at the time of the corresponding event trigger (for example, the BeginRequest event, It fires when an application receives an HTTP request and is about to process it, invoking the method registered by the HTTP module, and the actual work is performed in these methods.. Net itself already has many HTTP module, including form validation module ( FormsAuthenticationModule), Session status Module (sessionstatemodule), output cache module (OutputCacheModule), and so on.

Registering the Http Module

Before registering our own Http Module, let's take a look at the HttpModule already in ASP. Similar to Http handler, we need to open the Web. config file in the C:\WINDOWS\Microsoft.NET\Framework\ v2.0.50727\config directory on the machine. To 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 "/>
... Slightly

Let's look at the node first, the Type property is similar to the Type property of the HTTP handler node described in the previous section, and represents the corresponding assembly. However, unlike HTTP handler, the module provides only a Name property, and there is no handler for specifying a specific (or using a wildcard * representing a category) file, such as path. This is related to the module's characteristics, and we know that the module is responding to events triggered in the application cycle, and for all requests submitted to aspnet_isapi.dll, even if the request is just like 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 that 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 the namespace and the 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, where I name it "Custommodulename". We can get the Httpmodulecollection collection through the Modules property of the application (HttpApplication), and then further get the HttpModule object through the Name property.

With the Name property, we can also write a handler for a custom HttpModule-exposed event in the Global.asax file in the format: void Modulename_eventname (object sender, EventArgs e). We'll do a more detailed introduction later.

ASP. NET built-in Http Modules

The following table lists the HTTP Modules built into ASP. C:\WINDOWS\Microsoft.NET\Framework\ V2.0.50727\config under the Web. config and its main role.

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-side authentication with cookie-based forms authentication
Passportauthentication System.Web.Security.PassportAuthenticationModule Client Authentication 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 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 later in a programmatic way.

IHttpModule interface

Having seen so much theoretical knowledge, this section will begin to write the program and implement its 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 an 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 another method.

The whole process is well understood:

    1. When the first resource of a site is accessed, ASP. NET creates an instance of the HttpApplication class that represents the site application and creates all the module instances that are registered in Web. config.
    2. The module's init () method is called when the module instance is created.
    3. Within the init () method, register the event exposed by the HttpApplication that you want to respond to. (The actual method needs to be written separately, simply by simply registering the method).
    4. The HttpApplication triggers various events in its application cycle.
    5. Invokes the method that the 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 delegate and event in C #.

Dispose (): It can do some cleanup work before garbage collection.

In summary: The implementation of a IHttpModule template is generally the case:

public class Moduledemo:ihttpmodule
{
public void Init (HttpApplication context) {
Registering the HttpApplication application BeginRequest event
Or it could be any other HttpApplication exposed event.
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 () {
}
}

Writes text to the HTTP request output stream via the HTTP module

In this example, we only use the BeginRequest event and the EndRequest event to illustrate the usage of the Http Module. We use this example to understand the basic usage of the Http Module.

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

public class Moduledemo:ihttpmodule
{
The Init method is used only to register a method for the desired event
public void Init (HttpApplication context) {
Context. BeginRequest + = new EventHandler (context_beginrequest);
Context. EndRequest + = new EventHandler (context_endrequest);
}

The actual code that handles the BeginRequest event
void Context_beginrequest (object sender, EventArgs e) {
HttpApplication application = (HttpApplication) sender;
HttpContext context = Application. Context;
Context. Response.Write ("

}

The actual code that handles 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 for the HttpApplication instance, and the event-handling method simply writes different content to the input stream of the HTTP request 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 that was created automatically when the site was built, typing a few words inside, in order to make a distinction, I entered the text that is located on the. aspx page. Then we open it in the browser and should see something like this:

Then we create a new default2.aspx, browsing in the browser, you can see that two pages have the same effect. This means that for different two files, the HTTP module has a role to play, and it can be seen that it is actually at the application level, not the page level.

Now, we open a picture file in the site, and found that it shows a red fork, why? Because the HTTP module is for HTTP requests, not one or a class of files, when requesting a picture, the HTTP module we write will still work, inserting text into a binary image, destroying the file format, and only showing the Red fork.

Note: If you find your picture is showing normal, don't be surprised, here's the thing: Recall that the first section we discussed, for picture files, is handled directly by IIS and will not be referred to aspnet_ Isapi.dll, therefore, the module cannot capture a request for a picture-type file. The workaround is to set it up in IIS.
It is important to note that if you use Vs2005 's own local Server, you do not need to set up IIS, and all images or any file types will be processed by Aspnet_isapi.dll.

Iterating through the HTTP module collection

We now look at the names of all the Http Module registrations to the application by traversing the Httpmodulecollection collection.

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 the Module names
string[] Modulenames = Modulecollection.allkeys;

System.Text.StringBuilder results = new System.Text.StringBuilder (); Traversing result Sets

foreach (string name in Modulenames) {
Get 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 ();
}

Then output it in the Page_Load method:

protected void Page_Load (object sender, EventArgs e)
{
Response.Write (Showmodules ());
}

We should be able to see a picture like this:

Compared to the table listed earlier, it can be seen that it is almost identical (more than one defaultauthentication). Another note to the bottom fourth line, that 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 knew this file. It is primarily used to place the responder for an application event or session event. We are familiar with Application_Start, Application_End, Session_Start, Session_End and so on.

In ASP. Glabal not only can register the application and session events, but also register the events exposed by the HTTP module, not only to register the events of the system module, but also to register the events that our own righteous module exposes. Before you start, here are two points to note:

    1. Application events are triggered every time an HTTP request is processed, except Application_Start and Application_End, which are triggered only when the first resource file is accessed.
    2. The Http module cannot register and respond to Session events, and for Session_Start and Session_End, it can only be handled by Glabal.asax.

Well, let's now modify the previous Moduledemo sample program, give it the following to add an event to it (in order to make the program concise, I made a simplification):

public class Moduledemo:ihttpmodule {

Declaring an Event
public event EventHandler Exposedevent;

The Init method is used only to register a method for the desired event
public void Init (HttpApplication context) {
Context. BeginRequest + = new EventHandler (context_beginrequest);
}

The actual code that handles the BeginRequest event
void Context_beginrequest (object sender, EventArgs e) {
HttpApplication application = (HttpApplication) sender;
HttpContext context = Application. Context;
Context. Response.Write ("


Onexposedevent (New EventArgs ()); Calling methods
}

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, adding the following code, noting 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 have 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:

Summarize

This article simply describes what an HTTP Module is. We first understood the role of the Http module, then we looked at the ASP. NET built-in module, then we introduced the IHttpModule interface, and through a simple example implemented this interface, finally we discussed the Http module and Global.asax file on your phone.

This article is simply a brief introduction to IHttpModule, more practical applications, will be added in the following articles.

Hope this article can bring you help!

Http Module Introduction

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.