Asp Net Web API 2.1 get client IP address

后端 未结 9 1071
逝去的感伤
逝去的感伤 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: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

提交回复
热议问题