ASP.NET low-level fun
Note: this entry has moved.
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
,
HttpResponse
and 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"];
// 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...