Welcome to the navigation

Adipisicing laborum, nulla duis minim proident, excepteur veniam, fugiat in pariatur, ad dolore quis cillum consectetur dolor dolor incididunt id eu exercitation sed sint ea. Nulla irure reprehenderit id enim ut anim consequat, magna sunt ex pariatur, excepteur dolor officia tempor ut cillum incididunt et velit adipisicing sed ullamco deserunt

Yeah, this will be replaced... But please enjoy the search!

Getting the Client IP via ASP.NET Web API

Categories Tags

I've seen some questions around the web regarding this, this version will return a string with the client IP. If it returns ::1 that means the client is requesting from the same computer as where the API is running. The query address will be something like http://yoursite/api/ip depending on your routing.

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)this.Request.Properties[RemoteEndpointMessageProperty.Name];
                return prop.Address;
            }
            else if (HttpContext.Current != null)
            {
                return HttpContext.Current.Request.UserHostAddress;
            }
            else
            {
                return null;
            }
        }
    }
}
Please note that this portal is a BETA site , I will continuously improve all functionality and performance during the coming weeks / the author