Tuesday, August 27, 2019

How to get Client IP from ASP.NET Web API HttpRequestMessage


Some times you will want to track the client who is calling your API and from which IP address the client made the call. Following method might help you to get client IP:

using System.Net.Http;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Http;


        private static string GetClientIp(HttpRequestMessage 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;
            }
        }

In case of calling from local machine it will return ::1 otherwise the client IP address.

Happy Learning

2 comments:

Please keep your comments relevant.
Comments with external links and adult words will be filtered.