Asp Net Web API 2.1 get client IP address

后端 未结 9 980
逝去的感伤
逝去的感伤 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条回答
  • 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;
    
    0 讨论(0)
  • 2020-11-27 11:27

    It's better to cast it to HttpContextBase, this way you can mock and test it more easily

    public string GetUserIp(HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey("MS_HttpContext"))
        {
            var ctx = request.Properties["MS_HttpContext"] as HttpContextBase;
            if (ctx != null)
            {
                return ctx.Request.UserHostAddress;
            }
        }
    
        return null;
    }
    
    0 讨论(0)
  • 2020-11-27 11:36

    I think this is the most clear solution, using an extension method:

    public static class HttpRequestMessageExtensions
    {
        private const string HttpContext = "MS_HttpContext";
        private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
    
        public static string GetClientIpAddress(this 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;
        }
    }
    

    So just use it like:

    var ipAddress = request.GetClientIpAddress();
    

    We use this in our projects.

    Source/Reference: Retrieving the client’s IP address in ASP.NET Web API

    0 讨论(0)
  • 2020-11-27 11:38
    string userRequest = System.Web.HttpContext.Current.Request.UserHostAddress;
    

    This works on me.

    System.Web.HttpContext.Current.Request.UserHostName; this one return me the same return I get from the UserHostAddress.

    0 讨论(0)
  • 2020-11-27 11:41

    With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress

    0 讨论(0)
  • 2020-11-27 11:42

    My solution is similar to user1587439's answer, but works directly on the controller's instance (instead of accessing HttpContext.Current).

    In the 'Watch' window, I saw that this.RequestContext.WebRequest contains the 'UserHostAddress' property, but since it relies on the WebHostHttpRequestContext type (which is internal to the 'System.Web.Http' assembly) - I wasn't able to access it directly, so I used reflection to directly access it:

    string hostAddress = ((System.Web.HttpRequestWrapper)this.RequestContext.GetType().Assembly.GetType("System.Web.Http.WebHost.WebHostHttpRequestContext").GetProperty("WebRequest").GetMethod.Invoke(this.RequestContext, null)).UserHostAddress;

    I'm not saying it's the best solution. using reflection may cause issues in the future in case of framework upgrade (due to name changes), but for my needs it's perfect

    0 讨论(0)
提交回复
热议问题