HttpHandlers and Http handler, httphandlers Processing

Source: Internet
Author: User

HttpHandlers and Http handler, httphandlers Processing

ASP. net http is a process (usually called "endpoint") that responds to requests to ASP. NET Web applications "). The most common handler is the ASP. NET page handler that processes. aspx files. When a user requests a. aspx file, the page uses a page handler to process the request.

ASP. NET page handler is only a type of handler. ASP. NET also includes several other built-in processing programs, such as Web service processing programs for. asmx files.

If you need special processing (you can use the file extension in the application for identification), you can create a custom HTTP handler. For example, the following scheme makes good use of the custom HTTP handler:

  • RSS sourceTo create an RSS feed for a site, you can create a processing program that can issue an rss xml format. Then, bind the. rss extension (for example) in your application to this Custom Handler. When a user sends a request ending with. rss to a site, ASP. NET calls your processing program to process the request.
  • Image ServerIf you want the Web application to provide images of different sizes, you can write a custom processing program to adjust the image size, and then return the adjusted image to the user as a response of the processing program.

The HTTP handler can access the application context, including the identity (if known) of the requesting user, application status, and session information. When an HTTP processing program is requested, ASP. NET calls the ProcessRequest method on the corresponding processing program. Processing ProgramProcessRequestMethod To create a response, which is then sent back to the requesting browser. As with any page request, the response will subscribe to all HTTP modules that handle events after the program runs. For more information about processing Web Server requests, see ASP. NET application lifecycle overview.

The HTTP handler can be synchronous or asynchronous. The synchronization handler returns the result after processing the HTTP request for which the handler is called. The asynchronous processing of the running process has nothing to do with sending a response to the user. Asynchronous processing is useful when you need to start an application process that may take a long time, and the user does not have to wait for the process to complete in order to get the response from the server.

Built-in HTTP handler in ASP. NET

ASP. NET maps HTTP requests to HTTP handlers based on file extensions. Each HTTP handler can process a single http url or URL extension group in an application. ASP. NET includes several built-in HTTP handlers, as listed in the following table.

Handler

Description

ASP. NET page handler (*. aspx)

Default HTTP handler for all ASP. NET pages.

Web Service Processing Program (*. asmx)

The default HTTP handler for Web service pages created using ASP. NET.

ASP. NET User Control Handler (*. ascx)

Default HTTP handler for all ASP. NET user control pages.

Trace. axd)

The handler that displays the trail information on the current page. For more information, see How to: Use the tracking viewer to view ASP. NET tracking information.

As shown in the preceding configuration, Handler added in. NET Framework configuration is followed by a bunch of actual Handler, but both are the same HttpFrobiddenHandler.

Create a custom HTTP handler

To create a custom HTTP handler, you can create a class that can implement the IHttpHandler interface to create a synchronous handler, or create a class that can implement IHttpAsyncHandler to create an asynchronous handler. Both handler interfaces require you to implement the IsReusable attribute andProcessRequestMethod.IsReusableAttribute specifies whether IHttpHandlerFactory objects (objects that actually call the appropriate handler) can place your handlers in the pool and reuse them to improve performance, or whether to create a new instance each time you need to process the program.ProcessRequestThe method is used to process a single HTTP request.

Create File Extension

When creating a class file as your HTTP handler, you can have your handler respond to any file extension that has not been mapped in IIS and ASP. NET. For example, if you create an HTTP handler to generate an RSS feed, you can map the handler to the extension. rss. To enable ASP. NET knows which handler will be used for your custom file extension, and must map the handler class file extension to ASP in IIS. and map the extension to your Custom Handler in your application.

By default, ASP. NET maps the file extension. ashx to a custom HTTP handler in the same way as it maps the extension. aspx to an ASP. NET page handler. Therefore, if you create an HTTP handler class with the file extension. ashx, the handler is automatically registered to IIS and ASP. NET.

To create a custom file extension for your handler, you must explicitly register the extension to IIS and ASP. NET. The benefit of not using the file extension. ashx is that your handler can then be reused for other extension mappings. For example, in an application, your Custom Handler may respond. the request ends with rss, and in another application, your Custom Handler may respond. the request at the end of the feed. For another example, your handler may map to two file extensions in the same application, but may create two different responses based on the extension.

The following example demonstrates how to create, register, and implement httpHandler.

Add the class ApkHandler implementation interface IHttpHandler to App_Code.

 

namespace FastDoge.Study{    public class ApkHandler : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            HttpRequest Request = context.Request;            HttpResponse Response = context.Response;            // This handler is called whenever a file ending             // in .sample is requested. A file with that extension            // does not need to exist.            Response.Write("

 

 

 

Register Hanler in Web. config. Here there will be differences between two different versions of IIS.

Add the following configuration for Web. config running in IIS 6.0 and IIS 7.0 classic modes

    

 

The verb specified predicate list can be a comma-separated HTTP predicate list (for example, "GET, PUT, POST"), or a start script ing (for example, asterisk [*] wildcard ).

Path: the specified path attribute can contain a single URL path or a simple wildcard string (for example, *. aspx ).

Type: Specifies a comma-separated class/assembly combination. ASP. NET first searches for the Assembly DLL in the dedicated \ bin directory of the application, and then searches for the Assembly DLL in the system assembly cache.

The IIS7 integration mode configuration is as follows:

  <system.webServer>    

 

Enter a url suffixed with apk in the browser after running.

As mentioned in MSDN, you can register in IIS through the graphical interface. Here you will not try it. Refer to https://msdn.microsoft.com/zh-cn/library/bb515343 (v = vs.100). aspx. Of course, if it is not added to the configuration file, if it is specified in HttpModule, it should be coupled with HttpModule, as mentioned in the previous article, call HttpContext. remapHandler method, as shown in the MyModule class mentioned in the previous article.

        private void Application_BeginRequest(Object source,        EventArgs e)        {            HttpApplication application = (HttpApplication)source;            HttpContext context = application.Context;            context.Response.Write("

 

Remove the Web. config configuration and access the above URL has the same effect.

Asynchronous HTTP processing program

An asynchronous HTTP processing program can be used to start an external process (for example, a method call to a remote server), and then process the program without waiting for the end of the external process. During asynchronous HTTP processing, ASP. NET puts the threads typically used for external processes back into the thread pool until the handler receives a callback from the external process. This avoids thread blocking and significantly improves performance because the number of threads that can be executed at a time is limited. If many users are requesting synchronous HTTP processing programs that depend on external processes, the operating system may soon run out of all threads because a large number of threads are blocked and waiting for external processes.

When creating an asynchronous processing programIHttpAsyncHandlerInterface, you must also implement BeginProcessRequest to start asynchronous calls to process a single HTTP request. You must also implement the EndProcessRequest method to clear code when the process ends.

The following defines an AsyncApkHandler asynchronous processing program, which calls an AsynchOperation during BeginProcessRequest. This class implements the IAsyncResult interface, and the code that requires asynchronous operations is called in the method StartAsyncWork ().

 

namespace FastDoge.Study{    public class AsyncApkHandler : IHttpAsyncHandler    {        public bool IsReusable { get { return false; } }          public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)        {            context.Response.Write("<p>Begin IsThreadPoolThread is " + Thread.CurrentThread.IsThreadPoolThread + " " + DateTime.Now + "  " + Thread.CurrentThread.ManagedThreadId + "</p>\r\n");            AsynchOperation asynch = new AsynchOperation(cb, context, extraData);            asynch.StartAsyncWork();            return asynch;        }        public void EndProcessRequest(IAsyncResult result)        {            if (result is AsynchOperation)            {                (result as AsynchOperation).Context.Response.Write("<p>End IsThreadPoolThread is " + Thread.CurrentThread.IsThreadPoolThread + "  "+DateTime.Now+"  " + Thread.CurrentThread.ManagedThreadId + "</p>\r\n");            }        }        public void ProcessRequest(HttpContext context)        {            throw new InvalidOperationException();        }    }    class AsynchOperation : IAsyncResult    {        private bool _completed;        private Object _state;        private AsyncCallback _callback;        private HttpContext _context;        bool IAsyncResult.IsCompleted { get { return _completed; } }        WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } }        Object IAsyncResult.AsyncState { get { return _state; } }        bool IAsyncResult.CompletedSynchronously { get { return false; } }        public HttpContext Context        {            get            {                return _context;            }        }        public AsynchOperation(AsyncCallback callback, HttpContext context, Object state)        {            _callback = callback;            _context = context;            _state = state;            _completed = false;        }        public void StartAsyncWork()        {            ThreadPool.QueueUserWorkItem(new WaitCallback(StartAsyncTask), null);        }        private void StartAsyncTask(Object workItemState)        {            Thread.Sleep(3000);            _context.Response.Write("<p>Completion IsThreadPoolThread is " + Thread.CurrentThread.IsThreadPoolThread + "  " + DateTime.Now + " " + Thread.CurrentThread.ManagedThreadId + "</p>\r\n");            _context.Response.Write("Hello World from Async Handler!");            _completed = true;            _callback(this);        }    }}

 

 

The configuration method is as follows. The effect is as follows:

Custom IHttpHandlerFactory class

IHttpHandlerFactoryClass receives requests and is responsible for forwarding requests to the corresponding HTTP handler. You can create an implementationIHttpHandlerFactoryInterface Class to create a custom HTTP handler factory. Creating a Custom Handler factory can better control the processing of HTTP requests, because different handlers can be created based on runtime conditions. For example, if you use a custom HTTP handler factory, you can instantiate an HTTP handler for a file type when the HTTP request method is PUT, and instantiate another HTTP handler when the method is GET. For example, by using an HTTP processing program factory, you can create a limited number of HTTP processing program objects to access expensive or limited resources such as database connections. Then, you can reuse these handler objects in future requests.

IHttpHandlerFactoryThere are two methods

IHttpHandler GetHandler: returns an instance of the class implementing the System. Web. IHttpHandler interface;

Void ReleaseHandler: enables the factory to reuse existing handler instances.

The following defines an ApkHanlderFactory and slightly modifies the content output by ApkHandler (outputs the HashCode of the current HttpHandler)

 

namespace FastDoge.Study{    public class ApkHanlderFactory : IHttpHandlerFactory    {        private ApkHandler _cacheHandler;        private ApkHandler CacheHandler        {            get            {                if (_cacheHandler == null)                {                    _cacheHandler = new ApkHandler();                }                return _cacheHandler;            }        }        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)        {            if (context.Request.QueryString.AllKeys.Contains("IsCache") &&                context.Request["IsCache"].ToLower().Equals("true", StringComparison.InvariantCultureIgnoreCase))            {                return CacheHandler;            }            return new ApkHandler();        }        public void ReleaseHandler(IHttpHandler handler)        {                    }    }}

 

 

The configuration file is basically the same as the registered IHttpHandler, except that the class name for implementing the IHttpHandlerFactory interface is filled in the type feature, but the method specified by encoding in the Module is not found yet, you may need to check the source code.

When the following URL is requested, the html content of the response remains unchanged.

If the IsCache parameter is removed, the content changes every time.

References

HTTP processing program Introduction

From

Overview of HTTP processing programs and HTTP modules

From

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.