We're writing an ASP.NET 5 (vNext) application that partly includes geocoding the user's location based on their IP address. We're attempting to grab the client's IP address using the following code found from a number of examples across the web:
var connection = context.HttpContext.GetFeature<IHttpConnectionFeature>();
if (connection != null) {
clientIpAddress = connection.RemoteIpAddress.ToString();
}
When we log the clientIpAddress
that comes from the IHttpConnectionFeature
, we find that the IP address is not correct.
However, we do notice that IIS is capturing the correct client IP address. We see this by inspecting the requests via the IIS control panel.
So, somewhere between the IIS request and our application code, the client's IP address is being modified, or our application code is not working properly with IIS. Or is it possible that IIS is performing extra work in deciphering the client's IP address - work that we need to mimic in our application code.
Why is the client's IP address correct in the IIS request logs, but not correct in our application code above? How do we grab the correct client IP address in our code?
Relevant software versions:
- ASP.NET 5 (vNext)
- KRE 1.0.0-beta2
- IIS 8
Update: We ran a .NET 4.5 application on the same IIS server that retrieves the IP address using Request.UserHostAddress
and it also retrieved the correct IP (the same one IIS is logging), so it seems to be an issue with the new .NET 5 code.