HttpHandler in web. config

Source: Internet
Author: User

HttpHandler

Many times, we create a new xxx. aspx page and xxx. aspx. the cs file is used to implement a very simple function, such as outputting xmlDom, logging out and redirecting, and having no html output. It is very troublesome to create a new page and delete unnecessary html, write the processing code in page_load. The use of HttpHandler does not need to be so troublesome.

You can use any language that complies with common language standards (CLS) to write custom HTTP handlers to process specific and predefined types of HTTP requests. The executable code defined in the HttpHandler class is used to respond to these specific requests, rather than the conventional ASP or ASP. NET Web pages. The HTTP processing program provides you with a way to interact with low-level requests and Response Services of the IIS Web server. It also provides functions that are very similar to ISAPI extensions but simple programming models.

For example, I need to implement a Logout. aspx page to log out and jump to. The following example mainly responds to the client's request for a page named logout. aspx to log out and jump. All requests to logout. aspx are provided by LogoutHttpHandler in WebUC. HttpHandler, The namespace in WebUC. dll of the Assembly.

Modify web. config and add the following script to <system. web> </system. web>:
<HttpHandlers>
<Add verb = "GET" path = "Logout. aspx" type = "WebUC. HttpHandler. LogoutHttpHandler, WebUC"/>
</HttpHandlers>
Among them, WebUC. HttpHandler. LogoutHttpHandler is the class for implementing the Logout. aspx function. WebUC is the dll of my web project. (For details, refer to msdn)

The following is the code of LogoutHttpHandler. It inherits the excuse to rewrite methods and attributes.

Using System;
Using System. Web;
Using System. Web. Caching;
Using System. Web. Security;

Namespace WebUC. HttpHandler
{

Public class LogoutHttpHandler: IHttpHandler
{
/// <Summary>
/// Enable HTTP Web request processing by implementing the custom HttpHandler interface of the IHttpHandler interface.
/// </Summary>
/// <Param name = "context"> HttpContext object, which provides reference for internal Server objects (such as Request, Response, Session, and Server) used to provide services for HTTP requests. </Param>
Public void ProcessRequest (HttpContext context)
{
FormsAuthentication. SignOut ();
Context. Response. Redirect ("Login. aspx", true );
}

/// <Summary>
/// Obtain a value indicating whether other requests can use the IHttpHandler instance.
/// </Summary>
Public bool IsReusable
{
Get
{
Return false;
}
}
}

}
}

After compilation, I can directly use http: // ***/logout. aspx is used to log out. In fact, there is no logout in my web directory. the aspx file can also be used in many aspects, such as preventing leeching and downloading statistics.

Http Handles in ASP. NET

I. About http handles
The request process of ASP. NET is based on a pipeline model. ASP. NET sends all http Requests (Requests) to the http component (modules) in the pipeline ). Each component performs corresponding actions after receiving an http request. After the http request passes all the http modules programs, it will be handled by an http handle program, and the processed results will be returned through the http modules in the pipeline. During this process, multiple http modules can be called, but only one http handle can be called. Its Process

It can be seen that each input http request is eventually processed by an http handle program. Http handle is an instance of classes that implement the System. Web. IHttpHandler interface, and some are similar to ISAPI extensions. In http handles, the following operations are implemented:
ProcessRequest: This method is used to process http requests. It is the core method of http handles.
IsReusable: an attribute that returns a bool value to indicate whether the http handle instance can be reused to process multiple http requests of the same type.

2. Register http handles in the configuration file
The http handles class can be registered in the web. config or machine. config file. In this way, the http handle class will be instantiated once an http request is input. In the web. config or machine. config file, we use the <HttpHandlers>
<Add verb = "supported http verbs" path = "path" type = "namespace. classname, assemblyname"/>
<HttpHandlers>

In <add>
1. the verb attribute describes the http request methods supported by the handle. For example, the post and get methods are supported, and the verb attribute is "POST, GET". If all request methods are supported, the verb attribute is "*".
2. The path attribute indicates which file requests are processed by calling the handle. For example, you only want to request my. this handle is called only when the possible file is used, and the path attribute is "my. possible ", if you want all files suffixed with possible (*. possible) is processed by the handle, and the path attribute is "*. possible ".
3. The namespace, class name, and accessory name (project name) of the handle class are specified in the type attribute ). ASP. NET runtime first searches for the dll of the accessory in the bin directory of the application program. If not, searches for the dll in GAC.

In fact, ASP. NET itself, many functions are also implemented using HTTP handlers, ASP. NET uses many handle classes for processing. aspx ,. asmx ,. soap and some other ASP.. NET file. You can find the following code in the machine. config file:
<HttpHandlers>
<Add verb = "*" path = "trace. axd" type = "System. Web. Handlers. TraceHandler"/>
 
<Add verb = "*" path = "*. aspx" type = "System. Web. UI. PageHandlerFactory"/>
 
<Add verb = "*" path = "*. ashx" type = "System. Web. UI. SimpleHandlerFactory"/>

<Add verb = "*" path = "*. config" type = "System. Web. HttpForbiddenHandler"/>
 
<Add verb = "GET, HEAD" path = "*" type = "System. Web. StaticFileHandler"/>
 
......
......
</HttpHandlers>
As shown in the preceding configuration. the request for the aspx file is sent to System. web. UI. pageHandlerFactory class for processing, and like. the config file is. web. httpForbiddenHandler class is used for processing. It can be guessed that this class will return an error that this class of files cannot be requested.

Iii. Implementation of the http handles class
Here we use C # To create a new handle class to handle new file types, such as files with. possible as the suffix.
1. Create a web application project named MyHandler in vs.net, and add a class file NewHandler. cs to create a class that implements the IHttpHandler interface:

Using System;
Using System. Web;

Namespace MyHandler
{
/// <Summary>
/// Summary description for NewHandler.
/// </Summary>
Public class NewHandler: IHttpHandler
{
Public NewHandler ()
{
//
// TODO: Add constructor logic here
//
}

# Region Implementation of IHttpHandler
Public void ProcessRequest (System. Web. HttpContext context)
{
HttpResponse objResponse = context. Response;
ObjResponse. Write ("ObjResponse. Write ("</center> </body> }

Public bool IsReusable
{
Get
{
Return true;
}
}
# Endregion
}
}
In the implementation of the ProcessRequest method, we simply get the HttpResponse object of HttpContext and send some html like the client. Returns true in the IsReusable implementation, indicating that the handle class instance can process multiple requests to the. possible file.

Note: If you want to use session in HTTP handlers, you also need to implement the IRequiresSessionState interface. The IRequiresSessionState interface is only a flag and does not need to implement any specific methods, so you only need to change the class declaration to: public class NewHandler: IHttpHandler and IRequiresSessionState.

2. Open the web. config file and register the newly created handle class above:
<HttpHandlers>
<Add verb = "*" path = "*. possible" type = "MyHandler. NewHandler, MyHandler"/>
</HttpHandlers>

3. Add the ISAPI extension in IIS and add our new suffix. possible. The specific process is as follows:
IIS -- select "default website", right click -- select "properties" -- "main directory" -- "configuration" -- click "add" in "ing" -- in the displayed dialog box, click "Browse, select the aspnet_isapi.dll file and enter possible in the extension, as shown in:

Click OK.

In this way, you can enter http: // localhost/MyHandler/xxx. possible in the browser to call the handle. Of course, here is just a simple example, so inputting any *. possible is the same effect. We can analyze the request url in the ProcessRequest method of NewHandler, and then make different responses according to different URLs. For example, we can jump to different real aspx pages, this is exactly one of the core parts of the MVC Pattern Implemented by Front Controller in asp.net in web design pattern. For details, see: http://msdn.microsoft.com/architecture/patterns/default.aspx? Pull =/library/en-us/dnpatterns/html/DesFrontController. asp.

Related Article

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.