Asp Net Web API 2.1 get client IP address

后端 未结 9 1069
逝去的感伤
逝去的感伤 2020-11-27 11:12

Hello I need get client IP that request some method in web api, I have tried to use this code from here but it always returns server local IP, how to get in correct way ?

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 11:24

    Following link might help you. Here's code from the following link.

    reference : getting-the-client-ip-via-asp-net-web-api

    using System.Net.Http;
    using System.ServiceModel.Channels;
    using System.Web;
    using System.Web.Http;
    
    
    namespace Trikks.Controllers.Api
    {
        public class IpController : ApiController
        {
              public string GetIp()
              {
                    return GetClientIp();
              }
    
              private string GetClientIp(HttpRequestMessage request = null)
              {
                    request = request ?? 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)request.Properties[RemoteEndpointMessageProperty.Name];
                         return prop.Address;
                    }
                    else if (HttpContext.Current != null)
                    {
                        return HttpContext.Current.Request.UserHostAddress;
                    }
                    else
                    {
                          return null;
                    }
               }
         }
    }
    

    Another way of doing this is below.

    reference: how-to-access-the-client-s-ip-address

    For web hosted version

    string clientAddress = HttpContext.Current.Request.UserHostAddress;
    

    For self hosted

    object property;
            Request.Properties.TryGetValue(typeof(RemoteEndpointMessageProperty).FullName, out property);
            RemoteEndpointMessageProperty remoteProperty = property as RemoteEndpointMessageProperty;
    

提交回复
热议问题