user1615362
user1615362

Reputation: 3807

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

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

Upvotes: 18

Views: 18341

Answers (3)

Garrett Fogerlie
Garrett Fogerlie

Reputation: 4458

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"];

Upvotes: 9

Sando
Sando

Reputation: 667

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

Upvotes: 19

Md. Nazrul Islam
Md. Nazrul Islam

Reputation: 3017

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

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

Upvotes: 10

Related Questions