How to Get User IP in ASP.NET MVC API Controller

17,539

Solution 1

IP = ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress;

Solution 2

I am using the following code and it work for me....

string ipAddress =   System.Web.HttpContext.Current.Request.UserHostAddress;

Solution 3

According to this, a more complete way would be:

private string GetClientIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        return ((HttpContext)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
    }
    else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
    {
        RemoteEndpointMessageProperty prop;
        prop = (RemoteEndpointMessageProperty)this.Request.Properties[RemoteEndpointMessageProperty.Name];
        return prop.Address;
    }
    else
    {
        return null;
    }
}

In the past, on MVC 3 projects (not API,) we used to use the following:

string IPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (String.IsNullOrEmpty(IPAddress))
    IPAddress = Request.ServerVariables["REMOTE_ADDR"];
Share:
17,539

Related videos on Youtube

user1615362
Author by

user1615362

Updated on September 14, 2022

Comments

  • user1615362
    user1615362 over 1 year

    I have tried the Request.UserHostAddress; but API controller doesn't have UserHostAddress inside Request.

  • muglio
    muglio almost 9 years
    I ended up doing a little extra research because it felt odd that you would pick up a request header in a server variable. context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] is picking up what is picking up the X-Forward-For request header sent by Proxy Servers and Load Balancers.
  • Pranav Labhe
    Pranav Labhe almost 9 years
    It gives host address
  • Igor Yalovoy
    Igor Yalovoy about 6 years
    HTTP_X_FORWARDED_FOR may contain multiple addresses.You should check for that. Example
  • himanshupareek66
    himanshupareek66 almost 6 years
    Is it not a typo "request" -> "Request" ??