Find Client Public IP Address Inside Controller of rest web API with out calling external api

Viewed 4315

I have a web API where I want to capture all incoming request public IP address inside my controller function.

1 Answers

Check below code this must return you IP address of client

   protected string GetUser_IP()
    {
        string VisitorsIPAddr = string.Empty;
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
        }
    return VisitorsIPAddr;
    }

For more help: Get public IP Address

Related