HttpWorkerRequest object in ASP. NET and Its Application

Source: Internet
Author: User

Position of the HttpWorkerRequest object in the ASP. Net processing process:

Each ASP. NET program will parse the current URL request during execution. This article will analyze the principles of ASP. NET page requests. When we enter a URL in a browser, the process is as follows:

The first step is the wwwserver capture (inetinfo.exe process). The process first judges the page suffix, and then decides to call the specific extension program according to the configuration in IIS.

For example, aspx calls aspnet_isapi.dll, which is then sent to w3wp.exe by aspnet_isapi.dll( iis Worker Process, which is called w3wq.exe in IIS6.0 and aspnet_wp.exe in IIS5.0 ).

W3wp.exe calls the. net class library for specific processing. The process is as follows:

ISAPIRuntime --> HttpRuntime --> HttpApplicationFactory --> HttpApplication --> HttpModule -- HttpHandlerFactory --> HttpHandle

1. ISAPIRuntime

The main function is to call some unmanaged code to generate an HttpWorkerRequest object. The HttpWorkerRequest object contains all the information of the current request and then passes it to HttpRuntime, the HttpWorkerRequest object generated here can be called directly on our page to obtain the original request information:

2. HttpRuntime
A. Generate HttpContext Based on the HttpWorkerRequest object. HttpContext includes attributes such as request and response;
B. Call HttpApplicationFactory to generate IHttpHandler (here a default HttpApplication object is generated, and HttpApplication is also an implementation of the IHttpHandler Interface)
C. Call the HttpApplication object to execute the request

3. HttpApplicationFactory.

It mainly generates an HttpApplication object:

First, check whether global exists. asax file, if any, use it to generate the HttpApplication object. here we can see global. the file name of asax is written to death in the asp.net framework and cannot be modified. If this file does not exist, use the default object.

4. HttpApplication

This is a complex and important object. The first step is to execute the initialization operation. The most important step is to initialize the HttpModule:

HttpApplication represents a Web application created by a programmer. HttpApplication creates an HttpContext object for this Http request. These objects contain many other objects related to this request, including HttpRequest, HttpResponse, and HttpSessionState. These objects can be accessed through the Page class or Context class in the program.

It reads the configurations of all httpmodules in web. config.

5. HttpModule

6. HttpHandlerFactory

7. HttpHandler

 

 

HttpWorkerRequest Application

1. Using HttpWorkerRequest for getting headers

First,HttpWorkerRequestClass is used internally by ASP. NET, and provides a lower-level way of accessing ASP. NET internals. in this code, we see that you can use the HttpContext to call GetService and get the current worker. then, you can use the same code that the intrinsic objects use, but with no overhead.

using System;using System.Web;public class Handler1 : IHttpHandler{    public void ProcessRequest(HttpContext context)    {        IServiceProvider provider = (IServiceProvider)context;        HttpWorkerRequest worker = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));        //        // Get the Referer with HttpWorkerRequest.        //        string referer = worker.GetKnownRequestHeader(HttpWorkerRequest.HeaderReferer);        //        // Get the Accept-Encoding with HttpWorkerReqest        //        string acceptEncoding = worker.GetKnownRequestHeader(HttpWorkerRequest.HeaderAcceptEncoding);        //        // Display the values.        //        HttpResponse response = context.Response;        response.Write("Referer: ");        response.Write(referer != null);        response.Write(" Accept-Encoding: ");        response.Write(acceptEncoding);    }    public bool IsReusable    {        get        {            return false;        }    }}

Description of the HttpHandler.This is a generic handler you can run in the code-behind file of a HTTP handler. you can use the contents of the ProcessRequest method anywhere in ASP. NET, through. the first lines with IServiceProvider simply use an interface to get the HttpWorkerRequest.

Using the worker instance.The example shows how you can get the referer of the page and also the Accept-Encoding headers. you can do this with the Request object, but it is slower and more prone to errors. finally, the example prints the text of the headers it accessed.

2. Using HttpWorkerRequest for setting headers

Here we see how you can set HTTP headers with the HttpWorkerRequest. this allows you to bypass the ASP. NET AddHeader method, which has a fair amount of overhead. we specify that the handler shoshould be cached for 2 hours here. the SendKnownResponseHeader method is not exactly the same as AddHeader, but sometimes you can use it instead.

public void ProcessRequest(HttpContext context){    IServiceProvider provider = (IServiceProvider)context;    HttpWorkerRequest worker = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));    //    // Set Cache-Control with HttpWorkerRequest.    //    worker.SendKnownResponseHeader(HttpWorkerRequest.HeaderCacheControl, "private, max-age=7200");}
3. Gotchas with HttpWorkerRequest

TheHttpWorkerRequestIs not commonly used in simple or small ASP. NET projects, and it is much harder to use. for example, its settings can interact in different ways with your Web. config. setting the Content-Length is very tricky to get right. due to the complexity of the class, these are things you will have to hack through.

4. Performance of HttpWorkerRequest

Here we see a simple benchmark that compares setting two HTTP headers on a response. the first method uses the Response object, and the second method uses the HttpWorkerRequest object. internally, the first version will call into the same methods as the second version. in other words, the result is obvious from the internal layout of the runtime.

=== HTTP header method versions benchmarked ===public static void Set1(HttpContext context, string contentEncoding, string cacheControl){    context.Response.AddHeader("Content-Encoding", contentEncoding);    context.Response.AddHeader("Cache-Control", cacheControl);}public static void Set2(HttpContext context, string contentEncoding, string cacheControl){    IServiceProvider provider = (IServiceProvider)context;    HttpWorkerRequest worker = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));    worker.SendKnownResponseHeader(HttpWorkerRequest.HeaderContentEncoding, contentEncoding);    worker.SendKnownResponseHeader(HttpWorkerRequest.HeaderCacheControl, cacheControl);}=== Calling code (1 million iterations) ===Set1(context, "gzip", "private, max-age=7200");Response.ClearHeaders();Set2(context, "gzip", "private, max-age=7200");Response.ClearHeaders();=== Benchmark results ===Set1 Response:          895 ms     Note:              Uses AddHeaderSet2 HttpWorkerRequest: 488 ms     Note:              Uses SendKnownResponseHeader
5. Intrinsic objects in ASP. NET

You can accomplish almost everything thatHttpWorkerRequestLets you do with the Context, Request and Response insic objects. However, when you use Request and Response, they execute complicated and slow logic. Eventually, these objects then use HttpWorkerRequest themselves.

Example of using referer.When you call the UrlReferer property on Request, the property does several string comparisons and then creates a new Uri object. this causes a heap allocation. if you check the UrlReferer on every request, this overhead can add up.

AppendHeader method.When you open the AppendHeader method in ASP. NET, you will find a lot of complex logic and error checking. often you do not need all this overhead. internally, the method also callinto the HttpWorkerRequest.

6. Resources

You have very likely seenMSDNTopic about this class, but it bears repeating. it states that usually "your code will not deal with HttpWorkerRequest directly. "However, it adds that this may be necessary to implement if you are implementing your own hosting environment. [HttpWorkerRequest Class-MSDN]

An excellent blog resource.The most helpful resource on using this class directly is by Daniel Cazzulino. he shows how you can use GetKnownRequestHeader for very specific requirements relating to networks. [ASP. NET low-level fun-Daniel Cazzulino's Blog-weblogs.asp.net]

7. Real-world results with HttpWorkerRequest

The author modified his code to useHttpWorkerRequestIn 4 places. The result is that each request is processed about 20 microseconds faster. These timings are real-world and use the accurate Stopwatch class on the requests.

8. Summary

Here we saw how you can use the 'secret'HttpWorkerRequestTo develop web applications that are faster and have clearer code in some respects. this is considered a lower-level interface to ASP. NET, and it shoshould be used with care and testing. for scalability and performance, the HttpWorkerRequest is superior. using it CES allocations and avoids lots of code execution.

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.