ASP. NET processing program (fifth article)

Source: Internet
Author: User
Tags visual studio 2010

The HttpApplication has 19 standard events that, when it reaches the 8th event Postmaprequesthandler Trigger, indicates that a handler object has been acquired to process the request. After the 11th event PreRequestHandlerExecute, HttpApplication will execute this handler.

Problem:

    1. HttpApplication How do I choose a handler?
    2. What is the handler object?
    3. HttpApplication How do I get this handler object?
First, processing procedures

For different requests, ASP. NET requires different processing, and it is processed separately by various handlers in ASP. Typically, the handler is determined based on the extension of the request. In fact, many handlers have been pre-defined in ASP.

  1, the relationship between the processing procedure and the HttpApplication

In ASP. NET, the real processing of the request is in the handler. The handler is responsible for completing the actual request processing, and for the developer, most of the development work is carried out around the processing program. In fact, there is not a lot of contact with HttpApplication event processing, HttpApplication in addition to the role of processing programs can be understood as a handler for processing pre-processing and post-processing work.

Handlers have different names in different Web development technologies, called HttpHandler in ASP.

  2, the handler interface IHttpHandler and IHttpAsyncHandler

In ASP., all handler classes must implement the IHttpHandler interface or implement the IHttpAsyncHandler interface, one synchronous, one asynchronous.

IHttpHandler is defined as follows:

    Public interface IHttpHandler    {        bool isreusable {get;}        void ProcessRequest (HttpContext context);    }

This is what is achieved in the general handler.

    • ProcessRequest is the primary method of the IHttpHandler interface, receiving and passing a HttpContext-type request context object, which the handler can get information about to process the request. An object that can be responded to by HttpContext's response property, which returns the results of the server's processing to the client.
    • The IsReusable property indicates: "When this handler object is used, it can be cached and reused in subsequent request processing, which is primarily used in conjunction with the handler factory."

An asynchronous handler derives from a handler interface that is synchronized, and the interface is defined as follows:

    Public interface Ihttpasynchandler:ihttphandler    {        IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, Object extradata);        void EndProcessRequest (IAsyncResult result);    }

Two methods, BeginProcessRequest and EndProcessRequest methods were added than IHttpHandler. Same as with other async methods.

  3. Using sessions in handlers

Handlers are the basic unit of processing requests in an ASP. By default, session state is not even available in handlers, which can increase the speed of site processing. For handlers that require read-write session state, a specific token interface irequiresessionstate must be implemented, This interface is defined in the namespace System.Web.SessionState, where no members are defined, so implementing this interface does not require adding any members to the class. Similarly, the interface defined under this namespace ireadonlysessionstate also does not define any programs to flag handlers that only need to read the session state.

This interface, which does not have any members, is often referred to as the labeled interface, and it appears to be due to. NET early without tags (Attribute) and in a flash, this is the only example in ASP.

HttpApplication the 9th Event AcquireRequestState event and the 13th event ReleaseRequestState, HttpApplication the processing of the request state by judging whether the object that has been obtained by the handler implements these interfaces.

  4, the processing program factory

The class that implements the handler interface can be used to create a handler object for direct use, and if you mate with a handler factory, you can implement the management of the handler object.

For example, instead of creating a new object every time a handler is created, a pool of handler objects can be used to get an existing object out of the pool and use it directly to improve efficiency.

In ASP. NET, the class that is the handler factory must implement the interface IHttpHandlerFactory, which, under namespace system.web, is defined as:

    Public interface IHttpHandlerFactory    {        IHttpHandler GetHandler (HttpContext context, String RequestType,   String URL, string pathtranslated);    void Releasehandler (IHttpHandler handler);    }

Where the GetHandler method is used to get a handler object from this handler factory, the Releasehandler method is used to release a handler object.

The diagram is as follows:

  

  5. Registration Processing procedure

Each handler is used to process a class of requests, and the different request classes are differentiated by the requested extension, and the matching relationship between the handler and the request is set by configuration parameters in the Web site's configuration file, Web. config. The child element of the system.web configuration element httphandlers is used to configure the handlers used by the Web site. The httphandlers element can contain three seed elements: Add, remove, and clear.

The add child element has three required properties, which function as follows:

    1. Verb uses a comma (,) Split HTTP request Type list to represent the type of processing request, for example: Get,post, etc.; use an asterisk (*) to handle all types of requests.
    2. Path matches the requested URL through a fixed URL path or a wildcard using an asterisk (*), for example, using *.aspx to indicate that the processing request will handle all requests that have an ASPX extension.
    3. The type name of the handler, or the type name of the handler factory, which must be the full name of the type, containing the namespace, the assembly, when the class is placed in a private assembly.
    4. Validate is an optional property, and if set to False, ASP. NET will not attempt to load the class until the first matching request is called.

If we define a handler class, this class is defined under namespace MyHandler, named Validatecodehandler, This class is defined in the private assembly MyHandler.dll, which is used to handle a get type request with the extension VC, then the configuration parameters are as follows:

<configuration> <system.web> 

When the site application is running, the actual configuration file is derived from the system's Machine.config, the system's Web. config, and the web. config of the site itself is merged. In Web. config, ASP. NET has pre-configured the mapping of handlers in 57, and programmers can extend their custom handlers through the handler interface.

  6. Generate the verification code using the handler program

CAPTCHA is a security technique commonly used in web development to prevent malicious attacks.

We use a handler to generate a picture of the CAPTCHA sent to the client, which requires the following steps to complete this handler:

    1. Create a Class library project MyHandler, the default namespace for the new project is also MyHandler.
    2. Add a new class Validatecodehandler in the Class Library project MyHandler to implement the IHttpHandler interface. In order to use session state management in handlers, implement the IRequiresSessionState interface at the same time.
    3. Complete the operation of the Authenticode generated in the ProcessRequest method.
    4. Reference this class library project in a Web site project.
    5. Register the handler in the Web site project's configuration file, Web. config.
    6. Use the verification code generated by the handler on the page that requires the code.

Create a new ASP. NET Web program:

    public class Validatecodehandler:ihttphandler,irequiressessionstate {private static random random = new R        Andom (); public void ProcessRequest (HttpContext context) {context.            Response.ContentType = "Image/jpeg";            Image image = new Bitmap (60, 30); Generates a random number int code = random.            Next (1000, 10000); String codestring = code.            ToString (); Use session state context.            session["Code" = codestring;                using (Graphics g = graphics.fromimage (image)) {g.clear (Color.whitesmoke);                StringFormat SF = new StringFormat (); sf.                Alignment = Stringalignment.center; sf.                LineAlignment = Stringalignment.center; g.DrawString (codestring, New Font ("Arial", +), Brushes.blue, new RectangleF (0, 0, image.) Width, image.            Height), SF); } context.            Response.ContentType = "Image/jpeg"; Image. Save (context. Response.outPutstream, Imageformat.jpeg);        } public bool IsReusable {get {return false;} }

Then add the following configuration to the Web. config:

    

Then start the project and open up a path to the VC suffix under this system:

  

From the project we can see that all the. VC suffix paths, and ASP. NET will map to this class for processing.

II. General processing procedures

Although you can create handlers in a standard way, the steps to implement are more complex, and in order to facilitate the application of the handler in Web development, starting with ASP. NET 2.0, ASP. NET provides a handler called a generic handler that allows us to define a private handler with the extension ashx in a simpler way.

A generic handler created with Visual Studio 2010 will generate two files Handler1.ashx and Handler1.ashx.cs. Where the contents of the Handler1.ashx file are as follows:

<%@ WebHandler language= "C #" class= "Handler"%>

The contents of the corresponding code file Handler1.ashx.cs are shown in the following code. You can see very clearly that this is a class that implements the IHttpHandler interface, as follows:

    public class Handler1:ihttphandler    {public        void ProcessRequest (HttpContext context)        {            context. Response.ContentType = "Text/plain";            Context. Response.Write ("Hello World");        }        public bool IsReusable        {            get            {                return false;    }}}

A generic handler is actually a handler class that is mapped directly to the ASHX extension's request in the system's configuration file by ASP. This way, we don't need to configure it in the configuration file.

  1, the General processing program factory

For a generic handler, the program for which the extension is requested does not require the programmer to configure it in Web. config because the handler is already defined in the system configuration file, Web. config. So the browser can directly request an address with the extension ashx:

<add path= "*.ashx" verb= "*" type= "System.Web.UI.SimpleHandlerFactory" validate= "True"/>

With the configuration file, we can see that the request for the extension ashx is done by defining the Simplehandlerfactory handler factory under the namespace System.Web.UI.

When requesting a resource on a server with a ashx extension, simplehandlerfactory will find the corresponding ashx file, find the corresponding handler through this file, and finally, Simplehandlerfactory creates an instance of this type of handler object by reflection and returns it to HttpApplication through the GetHandler method, completing the final request processing.

  2, the use of general treatment procedures for the occasion

For an ASP, the most common result is an HTML Web page, where the work of generating a Web page is usually done using a Web form with an ASPX extension, which can be done with a generic handler for requests that do not result in HTML. For example, generate RSS fed,xml, images, etc.

A generic handler is the simplest and most efficient handler in an ASP. NET site, and it plays an important role in handling requests that return types are not HTML.

  3, the use of general processing procedures to generate a CAPTCHA picture

For example, in the previous implementation of the code handler with a generic handler can be done faster, directly in the ProcessRequest method to implement the function can be, the original 1th, 2, 4, 5 steps can be omitted.

    public class Handler1:ihttphandler, irequiressessionstate {private static random random = new random (); public void ProcessRequest (HttpContext context) {context.            Response.ContentType = "Image/jpeg";            Image image = new Bitmap (60, 30); Generates a random number int code = random.            Next (1000, 10000); String codestring = code.            ToString (); Use session state context.            session["Code" = codestring;                using (Graphics g = graphics.fromimage (image)) {g.clear (Color.whitesmoke);                StringFormat SF = new StringFormat (); sf.                Alignment = Stringalignment.center; sf.                LineAlignment = Stringalignment.center; g.DrawString (codestring, New Font ("Arial", +), Brushes.blue, new RectangleF (0, 0, image.) Width, image.            Height), SF); } context.            Response.ContentType = "Image/jpeg"; Image. Save (context. Response.outputstream, IMAGEFORMAT.JPEG);            } public bool IsReusable {get {return false; }        }    }

The general handler to use the session is also to implement the interface IRequiresSessionState.

  4. Use generic handler to generate JSON

code example:

    public class Uploadpercenthandler:ihttphandler    {public        void ProcessRequest (HttpContext context)        {            Person p = new person ();            P.id = 1;            P.name = "Shake Sacred cow";            JavaScriptSerializer JSS = new JavaScriptSerializer ();            String json = JSS. Serialize (p);             Context. Response.ContentType = "Application/json";            Context. Response.Write (JSON);        }        public bool IsReusable        {            get            {                return false;    }}} public class person    {public        int Id {get; set;}        public string Name {get; set;}    }

Output:

  

Third, the page processing program

ASP. NET uses a template to generate a handler. The template extension is ASPX, which builds the handler code from a built-in handler factory PageHandlerFactory to compile the aspx form of the template, and then returns the handler to the HttpApplication to complete the processing of the request. Template files in aspx form can be edited directly from a text editor.

  1. Page Processing factory

In the system configuration file of ASP., the following configuration has been made to see that for requests with the extension ASPX, this handler factory will be processed by PageHandlerFactory.

The configuration is as follows:

<add path= "*.aspx" verb= "*" type= "System.Web.UI.PageHandlerFactory" validate= "True"/>

This class is defined under namespace System.Web.UI and is defined as follows:

public class Pagehandlerfactory:ihttphandlerfactory

This is a typical handler factory that returns an instance of a handler object that implements the IHttpHandler interface. PageHandlerFactory will look for the ASPX file that matches the request name and then parse the template file to generate the corresponding page class through the code generation mechanism. This page class derives from the pages class, which is defined under namespace System.Web.UI, and the class is defined as:

public class Page:templatecontrol,ihttphandler

The relationship between the ASPX template file and the page class and the generated class is:

  PageHandlerFactory reads the ASPX file and parses the ASPX file to generate a class derived from page;

  The parsing and code generation of the ASPX template only occurs at the time of the first processing, and subsequent requests will directly use the assembly that has been compiled, so this process does not slow down the processing of the site.

  2. Create a page handler

Within PageHandlerFactory, the derived class of the page class is generated by parsing the specified ASPX file Pageparser This class, which is used to create an object instance of the paging program. This class is defined in the namespace System.Web.UI, and the complete definition is as follows:

public sealed class Pageparser

Pageparser has a static method

Getcompiledpageinstance (String virtualpath,string inputfile,httpcontext context)

The Getcompiledpageinstance method internally uses the BuildManager class to create a Page object instance, which is defined under the namespace System.Web.Compilation, and the complete class definition is as follows:

public sealed class BuildManager

BuildManager's Createinstancefromvirtualpath method generates a derived page class from code through the virtual path of the page, and then creates the Page object through reflection, with the following code:

public static Object Createinstancefromvirtualpath (String Virtualpath,type requiredbasetype)

  3. Generated code

For an ASPX template file, there will normally be a CS background code file with the same name, which defines a class with the same name as the page, which you can see from the code file that the class derives from the page.
PageHandlerFactory the ASPX file will generate two classes, a partial class with a similar name defined in the background code, which will be merged with the classes defined in the background code at compile time into a page derived class derived from page. However, in ASP. NET, the class that creates the actual Page object is not the class, but the second class that is generated, in general, the name of the class is the name of the page followed by the underscore and ASPX. This is the page class that actually creates the Page object.

Assuming there is a person.aspx, there should be a corresponding background code file Person.aspx.cs, which defines a derived class for the person page.

The pagehandlerfactory,person.aspx will generate two classes, some of which are class person and person_aspx. In this case, the person in the background code file will be merged with the generated partial class person at compile time into a full person class definition, and person_aspx is a page class derived from person to create the actual instance of the Page object.

  4. Using the page processing program

Since the page handlers are generated from templates, in most cases we can just create this aspx template, and HttpApplication will create this generated handler through PageHandlerFactory. Then use this handler to complete the server's processing tasks. Now, if we need to generate a Web page from a handler, we just need to design an ASPX page.

In some special cases, we need to create some programs that generate HTML output. However, these programs do not want to be directly requested by the client, so you can use Pageparser or BuildManager to create a custom handler to complete the processing task through the ASPX format template.

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.