Introduction to HttpHandler HttpModule

  • 2020-05-07 19:31:54
  • OfStack

Several very important objects are involved in the life cycle: HttpHandler,HttpModule,IHttpHandlerFactory, and their execution (sequence) is roughly the same: the client end sends a page request, which is intercepted by a process of IIS, which calls different page handlers (.asp -) depending on the page suffix of the request (.aspx) > asp.dll; .aspx- > ISAPI.dll). The page handler goes through the processing of HttpModule,HttpHandler: the former HttpModule is used for the processing of some events before and after the page processing, and the latter HttpHandler is used for the processing of the real page.
As mentioned earlier, HttpModule processes the page before and after the page is processed, so it does not affect the actual page request. It is usually used to add some information to the head or tail of each page (such as the version right statement), etc. We have seen some free space, after our page uploaded, when browsing, we found that there are many small ads in the head and tail of each page. If you understand the principle of HttpModule, it is not difficult to do this ~


Differences between IHttpModule and IHttpHandler
Note :Module depends on which event you are responding to. 1 events were run before Handler and 1 after Handler
2. Processing of requests:
      IHttpModule is a size take all type, which is called regardless of the file requested by the client. For example, aspx,rar,html requests.
      IHttpHandler is a picky eater, and only the file types registered with ASP.net (such as aspx,asmx, and so on) are called.
3.IHttpHandler generates the content of the response according to your request. IHttpModule preprocesses the request, such as validating, modifying, filtering, etc., and also processes the response

 

ASP. Net configuration has many HttpHandler and HttpModule system itself, such as processing aspx. Net standard page file, and the page file the winning of event handling, etc. You can see these configurations by looking at the httpHandlers and httpModules nodes in the web.config file in the directory %System%/ Microsoft.NET \Framework\ v2.0.50727 \CONFIG. If you are interested, you can use Reflector to look up the relevant classes and methods in the.Net system to see how.Net handles and what it does.

Net also provides a mechanism to develop custom HttpHandler and HttpModule, both of which can be used for interception of HttpRequest to complete custom processing. HttpModule inherits the System.Web.IHttpModule interface and implements its own HttpModule class. There are two methods that must implement the interface: Init and Dispose. In Init, you can add events that need to be intercepted; Dispose is used for the release of resources. If you create your own resource object in Init, release it in Dispose.


namespace MyModule 
{ 
public class MyHttpModule : IHttpModule 
{ 
public MyHttpModule() 
{ 
} 
//Init Method to register HttpApplication  Events.  
public void Init(HttpApplication r_objApplication) 
{ 
r_objApplication.BeginRequest += new EventHandler(this.BeginRequest); 
} 
public void Dispose() 
{ 
} 
private void BeginRequest(object r_objSender, EventArgs r_objEventArgs) 
{ 
HttpApplication objApp = (HttpApplication)r_objSender; 
objApp.Response.Write(" Your request URL for " + objApp.Request.Path); 
} 
} 
} 

Copy the compiled dll file to the bin directory of the web project, and configure it in the web project web.config file system.web node:
This inserts the custom HttpModule class MyHttpModule into Pipeline of HttpModule of web. The main function of HttpModule is to intercept various events of Application and complete its own processing in these events. In fact, if you develop some projects yourself, it is enough to deal with them directly in Global.asax. If you are developing an Framework or some aspect of the component, you need to add processing in the event. If you are developing a custom HttpModule, you can avoid using Framework or the component and have to manually add code in Global.asax.         currently has in mind the purposes of developing custom HttpModule, such as global identity/permission verification, custom site access/operation log recording, monitoring and tracking the site for administration/debugging purposes, etc. Of course, if Framework is developed in conjunction with the custom HttpHandler, HttpModule can be used for other special processing.

        < httpModules >
            < add name="test" type="MyHttpModuleTest.MyHttpModule,MyHttpModule"/ >
          < /httpModules >
Note that     is case-sensitive because web.config is case-sensitive as an XML file. "type= MyHttpModuleTest.MyHttpModule,MyHttpModule" tells us that the system will pass the http request request to the MyHttpModuleTest.MyHttpModule class in the MyHttpModule.dll file. HttpHandler is a complete interception of Http Request.
First, it inherits the System.Web.IHttpHandler interface to implement its own HttpHandler class. The ProcessRequest method and IsReusable properties of the interface must be implemented. The ProcessRequest method completes the processing of each Http Request and sends HTML of the processing result to the output cache. The IsReusable attribute is called by.Net Framework to determine whether this instance of HttpHandler can be reused for other Request processing of the same type.
      if you need to read or write Session in your HttpHandler class, you need to inherit IRequiresSessionState. This interface does not have any methods, just a token interface. After inheriting this interface, you can access Session in your own HttpHandler and write values in Session.


namespace MyHandler 
{ 
public class MyHttpHandler : IHttpHandler, IRequiresSessionState 
{ 
public MyHttpHandler() {} 
public bool IsReusable 
{ 
get { return true; } 
} 
public void ProcessRequest(HttpContext context) 
{ 
HttpResponse objResponse = context.Response ; 
objResponse.Write("This request is handled by MyHttpHandler"); 
} 
} 
} 

Copy the compiled dll files into the bin directory of the web project.
Next, test 1 for MyHttpHandler in this way. We configured a file type with the suffix.cc for IIS, using the MyHttpHandler we wrote.
First, in the Configuration configuration of the IIS site, add a pair of Application Extention Mapping items with the cc suffix.
Then, in the web.config node node of the web project, configure:

MyHttpHandler, MyHandler"/ >

The verb property configures this HttpHandler to handle those HTTP methods, such as GET, POST, and so on, using * if all methods are handled. The path property configures which files HttpHandler processes, for example myfile.cc, or *.cc if all.cc files are processed.
Thus, all access to.cc files on this site is handled by MyHttpHandler. Visit the test site using http://localhost/ site virtual directory/a.cc to see the results of the test. Of course, a.cc does not exist on the Web server.

The typical use of HttpHandler is Web MVC open source project Maverick. Maverick USES one Dispatcher class to intercept all Http Request. He submits a request to Web server with the suffix.m. Each command and view on chain are processed in turn. The processing results of each command and view may be processed by selecting different processing branches in chain. The Step of each process writes the HTML of the processing results to the cache of Response for output.
Overall, the Maverick framework architecture concept is very good, but there are also obvious flaws, later I will have time to write about its architecture and need to improve.

In a word, the combination of HttpModule, HttpHandler and the encapsulation of the client with Ajax can bring great room for improvement in the development of web project.

Asp.Net HttpHandler implements URL rewrite
We often see many articles website use is * * *. Only when html or * * *. shtml (such as the log of this blog access effect), at the time of this writing the file on the server does not exist, then why can appear such effect, because Web server to perform the URL rewritten, their visit URL according to specific format rewritten into internal access page, it is convenient for users to understand the benefits of, at the same time also can better income your site search engine, of course, there are many other benefits, I'm not going to do 11 here.
This article is to use Asp.Net HttpHandler to achieve URL rewrite, the principle of its implementation is shown here, this program can handle any Url, because I used URL in the program to worry, only access to the file name is a number to handle, and refers to the internal execution of a new page, and output data, the code is as follows:
 
public void ProcessRequest(HttpContext Context) 
{ 
try 
{ 
// statement Request 
HttpRequest Request = Context.Request; 
// Take route Url Absolute path  
string Url = Request.Url.AbsolutePath; 
// Get access to Web The number of start character intervals of a file  
int RegStart = Url.LastIndexOf("/") + 1; 
// statement 1 A sure Web Is the file name all Numbers  
Regex Reg = new Regex(@"\d+"); 
// Match with a regular expression  
if (Reg.IsMatch(Url, RegStart)) 
{ 
// if web If the file name is a number, it is determined to query the relevant article and execute the specified page  
Context.Server.Execute("~/PermaLink.aspx?id=" + Reg.Match(Url, RegStart).Value); 
} 
} 
catch 
{ 
Context.Response.Redirect(Context.Request.Url.ToString()); 
} 
} 

Of course, the first thing you need to do is build a class and inherit from IHttpHandler, then copy the code in, and compile it. To use this feature in the Web project, add the following statement to web.config:
< httpHandlers >
< add verb="*" path="*.shtml" type="HttpHandle.UrlRewrite" / >
< /httpHandlers >
Also, configure the Web project in IIS. In the properties of the Web project, in the home directory TAB, change the execution permission to "scripts and executables", then open the configuration and add the file format extension to the application extension that needs to be overridden.


Related articles: