HttpHandler HttpModule Introductory Article _ Practical Tips

Source: Internet
Author: User
Tags httpcontext

Several very important objects are involved in the lifecycle: Httphandler,httpmodule,ihttphandlerfactory, whose execution (order) is roughly executed: The client side sends a page request and is intercepted by a process in IIS, It invokes a different page handler (.asp->asp.dll;. Aspx->isapi.dll), depending on the page suffix (. aspx) requested. While the page handler is in the process, it has to go through the HttpModule, HttpHandler processing: The former HttpModule for the processing of the page before and after the processing of some events, the latter HttpHandler for real page processing.
As mentioned earlier, HttpModule will process 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 (such as a copyright notice) to the head or tail of each page. Have seen some free space, our page upload up, browse the time found, in each page of the head and tail more than a lot of small ads ..., if you understand the principle of HttpModule, It's not so hard to do this.


The difference arrangement between IHttpModule and IHttpHandler
1. Order IHttpModule first, after IHttpHandler. Note: module depends on which event you are responding to, some of the events were run before handler, and some were run after handler
2. On the processing of requests:
IHttpModule is a size-only type that is invoked whenever a client requests a file, such as a aspx,rar,html request.
IHttpHandler is a fussy type, and only asp.net file types (such as aspx,asmx, and so on) that are registered will be called.
3.IHttpHandler generates response content according to your request, ihttpmodule the request, such as validation, modification, filtering, etc., and can also handle the response

Asp. NET system itself is configured with many HttpHandler and HttpModule to handle ASPX, and so on. NET standard paging files, as well as standard event handling in these paging files. View the httphandlers and httpmodules nodes in the Web.config file in the%system%/microsoft.net\framework\v2.0.50727\config directory to see these configurations. If you are interested, you can use reflector to view the related classes and methods in the. NET system and understand. NET how to deal with and what to do.

. NET also provides a set of mechanisms to develop custom HttpHandler and HttpModule, which can be used to intercept HttpRequest and complete custom processing. HttpModule inherits the System.Web.IHttpModule interface and implements its own HttpModule class. You must implement two methods of the interface: Init and Dispose. In Init, you can add events that need to be intercepted, Dispose for the release of a resource, and release in Dispose if you create your own resource object in init.

Copy Code code as follows:

Namespace MyModule
{
public class Myhttpmodule:ihttpmodule
{
Public Myhttpmodule ()
{
}
The Init method is used to register the HttpApplication event.
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 ("The URL you requested is" + ObjApp.Request.Path);
}
}
}

Copy the compiled DLL file to the bin directory of the Web project and configure it in the Web.config file system.web node of the Web project:
    This inserts the custom HttpModule class Myhttpmodule into the HttpModule pipeline of the current web. The HttpModule main function is to intercept the events of application and complete its own processing in these events. In fact, if you develop some projects, directly in the global.asax processing is enough. If you are developing a framework or some aspect of a component, you need to add processing to the event, develop custom HttpModule, avoid using the framework or components, and manually add code to the Global.asax.      currently think of the development of custom HttpModule uses, have a global identity/authority validation, custom site access/operation log records, in the management/commissioning and other purposes of the site monitoring and tracking. Of course, if the framework is developed in conjunction with a custom HttpHandler, HttpModule can be used for some other special processing.

<add name= "test" type= "Myhttpmoduletest.myhttpmodule,myhttpmodule"/>
Note that you want to be case-sensitive because Web.config is case sensitive as an XML file. "Type=myhttpmoduletest.myhttpmodule,myhttpmodule" tells us that the system will be HTTP Request requests are handed to the Myhttpmoduletest.myhttpmodule class located in the MyHttpModule.dll file. HttpHandler is a complete intercept of HTTP request.
First, inherit the System.Web.IHttpHandler interface and implement your own HttpHandler class. You must implement the ProcessRequest method and IsReusable property of the interface. The ProcessRequest method completes the processing of each HTTP request, sending the HTML of the processing result to the output cache. The IsReusable property is called by the. Net framework to determine whether the instance of this HttpHandler can be reused for other request processing of the same type.
If you need to read or write session values in your HttpHandler class, you need to inherit an interface irequiressessionstate. This interface does not have any method, just a markup interface. After inheriting this interface, you can access the session in your own HttpHandler, and you can write values in the session.

Copy Code code as follows:

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 are handled by Myhttphandler");
}
}
}

Copy the compiled DLL file to the Web project's Bin directory.
Next, let's test the Myhttphandler. We configured a file type with the. cc suffix name for IIS, and we handled it with the Myhttphandler we wrote.
First, in the configuration configuration of the IIS site, add a application extention mapping entry that handles the. cc suffix name.
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, if all methods are handled, use *. The Path property configures which files are processed by HttpHandler, for example, can be myfile.cc, and if all. cc files are processed, use *.cc.
Thus, access to all. CC type files on this site is handled by Myhttphandler. You can see the test results by using the http://localhost/site virtual directory/a.cc to access the test site. Of course, a.cc This file does not exist on the Web server.

The use of HttpHandler is more typical. NET MVC Open source project Maverick. Maverick uses a dispatcher class to intercept all HTTP requests, and he submits the request to the Web server as a suffix of. m, in dispatcher, remove the suffix of. m, extract command name, This command name then loads the processing flow from the configuration file to form a chain, which in turn handles each command and view on the chain, and the results of the command and view processing may select different processing branches in the chain , each processing step outputs the HTML written to the processing result in the response cache.
Overall, the maverick framework concept is very good, but there are obvious flaws, and later have time to write down the details of its architecture and need to improve the place.

In short, the HttpModule, HttpHandler, and the use of Ajax, such as the encapsulation of the client, can give the development of Web projects a lot of room for improvement.

asp.net HttpHandler implements URL rewriting.
We often see a lot of Web site access to the article when the use of ***.html or ***.shtml (such as the log access effect of this blog), when this write file does not exist on the server, then why is this effect, because the Web server on the URL of the rewrite, the access to the URL based on a specific format to rewrite the internal access page to achieve, its benefits are easy to understand the user, while the search engine can better income your site, of course, the other benefits are many, here do not do one by one introduced.
This article is about using HttpHandler in asp.net to implement URL rewriting, the principle of its realization please see here, this program can handle any URL, because I use the URL in the program, only the Access file name is a number of processing, and refers to the internal execution of a new page, and output data, the code is as follows:
Copy Code code as follows:

public void ProcessRequest (HttpContext context)
{
Try
{
Affirm request
HttpRequest Request = context.request;
Absolute path to fetch URL
string Url = Request.Url.AbsolutePath;
Number of start character intervals for accessed Web files
int regstart = Url.lastindexof ("/") + 1;
Declare whether a Web filename is full of numbers
Regex Reg = new Regex (@ "\d+");
To match with a regular expression
if (Reg.ismatch (URL, Regstart))
{
If the Web file name is a number, the decision is to query related articles, 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 have to do is to build a class, and inherit from the IHttpHandler, and then copy the code into, and compile. To use this feature in a Web project, you need to add the following statement to the web.config:
<add verb= "*" path= "*.shtml" type= "Httphandle.urlrewrite"/>
Also, configure the Web project in IIS. In the properties of the Web project, in the Home Directory tab, change the execution permissions to "Scripts and executables," and then turn on the configuration, adding an extension of the file format that needs to be rewritten in the application extensions.

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.