Daniel Cazzulino's Blog : ASP.NET low-level fun

ASP.NET low-level fun

Sometimes you need low level information about the current request in a web application, such as the IP address of the physical network adapter the request came through (cool in clustered multi-NIC servers), or some other weird stuff you can't find in the higher-level view provided by HttpRequest, HttpResponseand friends.
Luckily, the HttpContext implements IServiceProvider, which means you can ask for services with the following code:

IServiceProvider provider = (IServiceProvider) HttpContext.Current;
// Get the request
HttpRequest util = (HttpRequest)
  provider.GetService(typeof(HttpRequest));

OK, I know... who on earth would use that instead of simply calling HttpContext.Current.Request??? Well, THE one thing you can get that there's absolutely NO other way of getting, is the current HttpWorkerRequest:

// Get the worker
HttpWorkerRequest wr = (HttpWorkerRequest)
  provider.GetService(typeof(HttpWorkerRequest));
// Get the NIC address!!!!
string addr = wr.GetLocalAddress();

Another very cool use is to retrieve known header values. Usually, you just get the header from the Request.Header collection by its name:

// Would return "Keep-Alive" if enabled.
string cn = Request.Headers["Connection"]; 
// Would return "gzip, deflate" for example.
string enc = Request.Headers["Accept-Encoding"];
but that's prone to errors, and you have to sort of guess the casing, etc. This is the cool way:
// Get the worker
HttpWorkerRequest wr = (HttpWorkerRequest)
  provider.GetService(typeof(HttpWorkerRequest));

string cn = wr.GetKnownRequestHeader(HttpWorkerRequest.HeaderConnection); 
string enc = wr.GetKnownRequestHeader(HttpWorkerRequest.HeaderAcceptEncoding);

Have a look at the class members , there are quite a few interesting things, now that you can call them ;)... and use them NOW, before they regret making such a beast available...

posted on Wednesday, December 10, 2003 8:01 PM by kzu

# ASP.NET中的HttpWorkerRequest对像及其应用 @ Sunday, August 09, 2009 3:18 AM

HttpWorkerRequest对像在ASP.Net中处理流程中的位置: 每一个ASP.NET程序执行时都会对当前URL的请求进行解析,本文将分析ASP.NET页面请求的原理。当我们在浏览器上...

Anonymous