Skip to content

Instantly share code, notes, and snippets.

@tmacharia
Created September 4, 2019 18:40
Show Gist options
  • Save tmacharia/2beb39f8dfdb43f43d4447faf0b2783b to your computer and use it in GitHub Desktop.
Save tmacharia/2beb39f8dfdb43f43d4447faf0b2783b to your computer and use it in GitHub Desktop.
Asp.Net Core Get Request IpAddress
public static string GetIpAddress(this HttpContext _context, bool tryUseXForwardHeader = true)
{
string ip = string.Empty;
/*-----------------------------------------------------------------------------------
| Todo support new "Forwarded" header (2014)
| https://en.wikipedia.org/wiki/X-Forwarded-For
|
| X-Forwarded-For (csv list): Using the First entry in the list seems to work
| for 99% of cases however it has been suggested that a better (although tedious)
| approach might be to read each IP from right to left and use the first public IP.
|
| http://stackoverflow.com/a/43554000/538763
|
|------------------------------------------------------------------------------------*/
if (tryUseXForwardHeader)
ip = _context.GetHeaderValueAs<string>("X-Forwarded-For").SplitCsv().FirstOrDefault();
// RemoteIpAddress is always null in DNX RC1 Update1 (bug).
if (!ip.IsValid() && _context?.Connection?.RemoteIpAddress != null)
ip = _context.Connection.RemoteIpAddress.ToString();
if (!ip.IsValid())
ip = _context.GetHeaderValueAs<string>("REMOTE_ADDR");
if (!ip.IsValid())
throw new Exception("Unable to determine caller's IP.");
if (ip.StartsWith("::ffff:"))
ip = ip.Replace("::ffff:", string.Empty);
return ip.Trim();
}
// Usage In Controller
protected string RequestIPAddress => HttpContext.GetIpAddress();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment