ASP.NET中的HttpWorkerRequest對像及其應用

來源:互聯網
上載者:User

HttpWorkerRequest對像在ASP.Net處理流程中的位置:

每一個ASP.NET程式執行時都會對當前URL的請求進行解析,本文將分析ASP.NET頁面請求的原理。當我們在瀏覽器上輸入一個URL時, 流程如下:

首先被WWW伺服器截獲(inetinfo.exe進程), 該進程首先判斷頁面尾碼, 然後根據IIS中配置決定調用具體的擴充程式。

如aspx就會調用aspnet_isapi.dll, 然後由aspnet_isapi.dll發送給w3wp.exe(iis 工作者進程,IIS6.0中叫做 w3wq.exe,IIS5.0中叫做 aspnet_wp.exe).

接下來就是w3wp.exe調用.net類庫進行具體處理,流程如下:

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

1. ISAPIRuntime

主要作用是調用一些Unmanaged 程式碼產生HttpWorkerRequest對象,HttpWorkerRequest對象包含當前請求的所有資訊,然後傳遞給HttpRuntime,這裡產生的HttpWorkerRequest對象可以直接在我們的頁面中調用的,通過它取得原始的請求資訊:

2. HttpRuntime
a. 根據HttpWorkerRequest對象產生HttpContext,HttpContext包含request、response等屬性;
b. 調用HttpApplicationFactory來產生IHttpHandler(這裡產生的是一個預設的HttpApplication對象,HttpApplication也是IHttpHandler介面的一個實現)
c. 調用HttpApplication對象執行請求

3. HttpApplicationFactory.

主要是產生一個HttpApplication對象:

首先會查看是否存在global.asax檔案,如果有的話就用它來產生HttpApplication對象,從這裡我們可以看到global.asax的檔案名稱是在asp.net的架構中寫死的,不能修改的。如果這個檔案不存在就使用預設的對象。

4. HttpApplication

這個是比較複雜也比較重要的一個對象, 首先是執行初始化操作,比較重要的一步就是進行HttpModule的初始化:

HttpApplication代表著程式員建立的Web應用程式。HttpApplication建立針對此Http請求的 HttpContext對象,這些對象包含了關於此請求的諸多其他對象,主要是HttpRequest、HttpResponse、 HttpSessionState等。這些對象在程式中可以通過Page類或者Context類進行訪問。

它會讀取web.config中所有HttpModule的配置

5. HttpModule

6. HttpHandlerFactory

7. HttpHandler

 

 

HttpWorkerRequest 的應用

1. Using HttpWorkerRequest for getting headers

First, the HttpWorkerRequest class 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 should 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

The HttpWorkerRequest is 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 that HttpWorkerRequest lets you do with the Context, Request and Response instrinsic 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 calls into the HttpWorkerRequest.

6. Resources

You have very likely seen the MSDN topic 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 use HttpWorkerRequest in 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' HttpWorkerRequest to 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 should be used with care and testing. For scalability and performance, the HttpWorkerRequest is superior. Using it reduces allocations and avoids lots of code execution.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.