ASP.NET Web API controller tip: how to read the client’s IP address?
Posted: (EET/GMT+2)
Working with ASP.NET Web API controllers is easy, and gives you plenty of power to handle various kinds of requests in a modern REST fashion. However, there are still some little things that aren't as easy as they could be.
One of such little things is the ability to read the API caller's (client's) remote endpoint address, or, in more traditional terms, the IP address from which the HTTP call is coming from. In regular ASP:NET MVC controllers, you can simply use the Request object to read the address, but in API controllers, you cannot do this directly.
Luckily, this is quite easy to fix. Here's an example that works when you're hosting your Web API application with IIS:
private string GetRemoteClientIpAddress(HttpRequestMessage request)
{
// when hosting on IIS, the "MS_HttpContext" property key is available
if (request.Properties.ContainsKey("MS_HttpContext"))
{
HttpContextWrapper context = (HttpContextWrapper)request.
Properties["MS_HttpContext"];
return context?.Request?.UserHostAddress ?? "(unknown)";
}
else
{
// if we got here, the remote client's IP address was not found
return "(unknown)";
}
}
Here, the general Request object available in the API controller actions methods (of type HttpRequestMessage) is passed in to the function. Then, one of the properties of this object (when running under IIS) is called "MS_HttpContext". This property can be cast to the type HttpContextWrapper, which in turn contains the property we're after: UserHostAddress.
The above method GetRemoteClientIpAddress returns this IP address, or "(unknown)" if for some reason the property "MS_HttpContext" cannot be found.
Remember, that if you are testing your application locally, the function will usually return "::1", which is the shorthand IPv6 address for your own computer, "localhost".
Hope this helps!