Created
January 3, 2023 16:35
-
-
Save mehdico/e68dafaa73c005801cc787aad6222612 to your computer and use it in GitHub Desktop.
Get Client Ip Address #dotnetcore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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