1

So far I was using this code in order to get the IP Address of a client in a WEB API Message Handler (using an extension).

    public static string GetClientIPAddress(this HttpRequestMessage request)
    {        

        if (request.Properties.ContainsKey("MS_HttpContext"))
        {
            return ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress.ToString();

        }
        else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
        {
          return ((RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]).Address.ToString();     

        }
        else
        {
            return null;
        }
    }

However today I discovered a simpler way that works just fine but still I am a bit worried which way is better to use:

 HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "0.0.0.0";
David Dury
  • 5,537
  • 12
  • 56
  • 94
  • 1
    Possible duplicate: [Get the IP address of the remote host](http://stackoverflow.com/questions/9565889/get-the-ip-address-of-the-remote-host). What is better depends on *how* your web api is hosted (web hosting on IIS, self-hosting or self-hosting using OWIN). – djikay Jul 02 '14 at 14:43
  • Hosted in Windows Azure Web Sites (IIS) ... so I guess the way I was using it before is the right way! – David Dury Jul 02 '14 at 14:58

0 Answers0