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 127.0.0.1) 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:

C#

1

2

3

4

5

6

7

8

publicstaticclassHttpRequestMessageExtensions

{

publicstaticboolIsLocal(thisHttpRequestMessage request)

{

varlocalFlag=request.Properties["MS_IsLocal"]asLazy<bool>;

returnlocalFlag!=null&&localFlag.Value;

}

}

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