I tried:
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
public static string GetClientIpAddress(HttpRequestMessage request)
{
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
return null;
}
according to:
Retrieving the client's IP address in ASP.Net Web API
this is the combined approach which should be valid for self host and webapi host. Unfortunately I get null
instead of the IP address.
I'm trying locally so I'd expect 127.0.0.1
or localhost
as the IP address
Here is an expanded version of what you have that works for me.
Assuming you are in a controller the above extension method allows for calls like: