Skip to content

Instantly share code, notes, and snippets.

@mehdico
Created January 3, 2023 16:35
Show Gist options
  • Save mehdico/e68dafaa73c005801cc787aad6222612 to your computer and use it in GitHub Desktop.
Save mehdico/e68dafaa73c005801cc787aad6222612 to your computer and use it in GitHub Desktop.
Get Client Ip Address #dotnetcore
public string GetClientIp()
{
var httpContext = _httpContextAccessor?.HttpContext;
if (httpContext == null)
return null;
var header = httpContext.Request.Headers["CF-Connecting-IP"].FirstOrDefault()
?? httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault()
?? httpContext.Request.Headers["HTTP_TRUE_CLIENT_IP"].FirstOrDefault()
?? httpContext.Connection.RemoteIpAddress?.ToString();
if (IPAddress.TryParse(header, out var ip))
return ip.ToString();
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment