ASP. IHttpHandler Introduction

Source: Internet
Author: User
Tags httpcontext

Asp. NET two processing interfaces commonly used in response to HTTP requests are IHttpHandler and IHttpModule.

In general, IHttpHandler is used to handle a specific type of request, such as the separate processing of each *.asp, *.aspx file. The IHttpModule is typically used to handle requests for common operations, such as requesting the page to perform some of the same check functions.

Let's take a look at the processing steps of the IIS server at the appropriate HTTP request. Asp. NET has the concept of pipeline (Pipeline), meaning that each ASP. In IIS there will be a series of corresponding operations in series to form a line-like sequence.

Asp. NET Pipeline Introduction

Let's take a look at the process sequence diagram for the pipeline:

It can be seen that after the request arrives, the implementation is HttpModule processed and then called HttpHandler's ProcessRequest () method to do the exact corresponding. Therefore, it is not difficult to understand why there are some checks that are common to all requests in HttpModule, and that the processing of specific class requests is placed in the HttpHandler class.

Code Practice IHttpHandler

The author recently contacted in the project to use IHttpHandler to realize the processing of the client interface call, here it is simple to discuss the simple interface design based on IHttpHandler.

There are only two members of the IHttpHandler interface:

1 public interface IHttpHandler2 {3     bool isreusable {get;} 4     void ProcessRequest (HttpContext context); 5}

The IsReusable property is to identify whether the HttpHandler object can be used by other instances, which we typically set to true. The ProcessRequest () method is a specific response request method, and we just put the specific business logic operations here.

First, create a new Web project and add a handler class:

1 public class Rayhandler:ihttphandler 2 {3 public     bool IsReusable 4     {5         get {return true;} 6     } 7
   
    8 public     void ProcessRequest (HttpContext context) 9     {Ten         context. Response.Write ("ASP. HttpHandler Demo. -- .");     }12}
   

The Rayhandler class implements the ProcessRequest () function of the IHttpHandler interface, where only a single text is printed directly.

Then, we need to add the following configuration in the Web. config file:

Path represents a URL match, such as *.ray, which indicates that the handler responds so a URL request that ends with ". Ray", verb means that the request method, such as Get/post, uses * to indicate that it matches all. The type indicates the handler class, Webapplication2.rayhandler is the class name, WebApplication2 refers to the name of the assembly under the Bin directory, as in the example, the assembly name is WebApplication2.dll , and there is no need to make a suffix here.

Start the site and enter the URL that ends with ". Ray" to see the following results:

IHttpHandlerFactory Overview

Sometimes we may have to deal with a number of different suffixes, one suffix for a handler class, and our web. config file looks like this:

If we have a lot of httphandler implementation classes, then our web. config file configuration is bound to look very verbose. Or in some cases, we need to use IHttpHandlerFactory when the program is running to determine which handler to respond to.

IHttpHandlerFactory is defined as follows:

public interface ihttphandlerfactory{    IHttpHandler gethandler (HttpContext context, string RequestType, String URL, String pathtranslated);    void Releasehandler (IHttpHandler handler);}

which

    • GetHandler (): Returns an instance that implements the IHttpHandler interface;
    • Releasehandler (): Allows factory to reuse an already existing handler instance.

Take the above Ray,RSS request as an example to implement the factory class:

1 public class handlerfactory:ihttphandlerfactory{2 public     IHttpHandler GetHandler (HttpContext context, string req Uesttype, string URL, String pathtranslated) {3         IHttpHandler handler = null; 4         string path = context. Request.PhysicalPath; 5         switch (Path) {6 case             ". Ray": 7                 handler = new Rayhandler (), 8 break                 , 9 case             "path.getextension. RSS ":                 handler = new RssHandler ();                 break;12             default:13                 break;14         }15         Handler;17     } public     void Releasehandler (IHttpHandler handler) {         //void21}22     }

In this case, the configuration in Web. config is as follows:

The implementation of the factory class to correspond to different specific handler functions, simplifying the configuration.

Extensible IHttpHandlerFactory

In the above implementation, if the program needs to increase the processing of the new suffix, it is necessary to modify the switch statement in GetHandler (), which can also raise errors or introduce other security risks. So, is it possible to keep the Handlerfactory class constant in subsequent expansions?

The answer must be yes. Readers who are familiar with design patterns should understand that this is a simple factory model, and we can implement the design patterns called advanced points in order to achieve the preceding functions.

In this case, we can also use the language features of the C # language-reflection. Through the reflection mechanism of C #, we can reflect the corresponding Hanlder type according to the suffix of the URL, as long as we have the suffix name of the URL with the handler class name to contract the corresponding relationship.

For example, we rewrite GetHandler () as follows:

Using System.Reflection; Public IHttpHandler GetHandler (HttpContext context, string RequestType, String url, string pathtranslated) {        IHttpHandler handler = null;        String path = context. Request.PhysicalPath;        String className = this. GetType (). Namespace + path.getextension (Path);        try{            Type type = Type.GetType (className);            if (type = = null) {                context. Response.Write (String. Format ("The handler for" {0} "not found", Path.getextension (Path)));            }                    Handler = (IHttpHandler) type. Assembly.createinstance (ClassName);        } catch (Exception ex) {            context. Response.Write (String. Format ("Request address error:" + ex.) Message));            handler = null;        }                return handler;    

At this point, you only need to place the handler class in the method under the same namespace of the Handlerfactory class and configure it correctly in Web. config. For example, if you have a Rayhandler class, you should add a configuration such as the following to automatically match:

Summarize

This article briefly introduces the usage of IHttpHandler in ASP, provides the implementation of ihttphandlerfactory in the processing of multiple handler requests, and finally, the use of C # The reflection mechanism improves an extensible multi-request handler implementation method. Https://www.cnblogs.com/Rayblog/p/6394315.html

ASP. IHttpHandler 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.