Created
September 4, 2019 18:40
-
-
Save tmacharia/2beb39f8dfdb43f43d4447faf0b2783b to your computer and use it in GitHub Desktop.
Asp.Net Core Get Request IpAddress
This file contains 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 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