0

I need to get IP address of client in asp.net Controller.

I use this Code:

string ip = string.Empty;
if (request.IsSecureConnection)
    ip = request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrWhiteSpace(ip))
{
    ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (string.IsNullOrWhiteSpace(ip))
    {
        ip = request.UserHostAddress;
    }
    else
    {
        if (ip.IndexOf(",", StringComparison.Ordinal) > 0)
        {
            ip = ip.Split(',').Last();
        }
    }
}

Sometime the ip is empty. Do you have any idea why? Why is ip null in Httpcontext.Current.Request?

IndieGameDev
  • 2,905
  • 3
  • 16
  • 29
  • Does this answer your question? [Asp Net Web API 2.1 get client IP address](https://stackoverflow.com/questions/22532806/asp-net-web-api-2-1-get-client-ip-address) – Liam Oct 07 '20 at 07:44
  • I'm presuming this is Web api as *asp.net Controller* could be one of multiple technologies – Liam Oct 07 '20 at 07:45

0 Answers0