4.21.2016

IP-Adresse des Client in einem Web.API 2.x Controler ermitteln

Nach dem Einbinden von System.ServiceModel funktioniert folgender Code:


private string GetClientIp(HttpRequestMessage request = null)
       {
           request = request ?? this.Request;

           if (request.Properties.ContainsKey("MS_HttpContext"))
           {
               return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
           }
           else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
           {
               RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)this.Request.Properties[RemoteEndpointMessageProperty.Name];
               return prop.Address;
           }
           else if (HttpContext.Current != null)
           {
               return HttpContext.Current.Request.UserHostAddress;
           }
           else
           {
               return null;
           }
       }

Keine Kommentare: