title: Can we get IP address in an MVC Ajax call
body: <p>I'm new to MVC &amp; looking at a method that is used in two instances in a controller. It is used to get the client's IP address.</p>
  
  <p><code>GetData</code> is triggered by an Ajax call from the front end. 
  <code>GetIpAddress</code> works fine in the <code>Index</code> method, but will it work inside <code>GetData</code> as it is a standalone method.</p>
  
  <pre><code>public class CommonController : Controller
  {
    public ActionResult Index()
    {
       string ip = GetIpAddress(Request);
    }
  
    [HttpPost]
    public ActionResult GetData()
    {
       string ip = GetIpAddress(Request);
    }
  }
  
  
  
  public static string GetIpAddress(HttpRequestBase request)
          {
              if (request != null)
              {
  
                  string ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                  if (string.IsNullOrEmpty(ipAddress))
                  {
                      ipAddress = request.UserHostAddress;
                  }
                  ipAddress = ipAddress.Split(',').First();
                  return ipAddress;
              }
              return string.Empty;
          }
  </code></pre>