Adding Request.IsLocal to ASP.NET Web API

I was recently asked how to filter out local requests in Web API. Indeed, one of the more useful things that developers got used to work with in traditional ASP.NET (and the System.Web.dll) was the ability to quickly check if a given request is a local one or not – by simply calling the IsLocal boolean property on HttpRequest.

This has been omitted from HttpRequestMessage in the new HTTP object model, around which Web API is built, but Web API still keeps track of that information under the hood, so you can easily write a simple extension method to bring back the old familiar syntax.

More after the jump.

Request.isLocal in Web API

In the old HTTP model (System.Web.dll), Request.IsLocal returned true if the IP address of the request originator was localhost (or or if the IP address of the request is the same as the server’s IP address.

While HttpRequestMessage indeed does not have IsLocal anymore, Web API will track this information in a Lazy<bool> inside the Request.Properties dictionary, under a rather vague MS_IsLocal key.

With this information, we can now write a very simple extension method:

This now allows you to simply call isLocal() anywhere in the Web API pipeline where the framework gives you access to the incoming request.

In an ApiController:

In a handler:

In a filter:

Or even in a formatter:

By the way – contrary to pulling this information out of HttpContext, this approach works for both web-host and self-host.

All in all – a very simple 2-line extension method, but quite useful for development purposes.